/**
  * Fills object with all standard items of a Notification record
  *
  * @param  cbpaidPayHandler     $payHandler
  * @param  int                  $test_ipn
  * @param  string               $log_type
  * @param  string               $paymentStatus
  * @param  string               $paymentType
  * @param  string               $reasonCode
  * @param  int                  $paymentTime
  * @param  string               $charset
  */
 public function initNotification($payHandler, $test_ipn, $log_type, $paymentStatus, $paymentType, $reasonCode, $paymentTime, $charset = 'utf-8')
 {
     $this->payment_method = $payHandler->getPayName();
     $this->gateway_account = $payHandler->getAccountParam('id');
     $this->log_type = $log_type;
     $this->time_received = Application::Database()->getUtcDateTime();
     $this->ip_addresses = cbpaidRequest::getIPlist();
     $this->geo_ip_country_code = cbpaidRequest::getGeoIpCountryCode();
     $this->notify_version = '2.1';
     $this->user_id = (int) cbGetParam($_GET, 'user', 0);
     $this->charset = $charset;
     $this->test_ipn = $test_ipn;
     $this->payer_status = 'unverified';
     $this->payment_status = $paymentStatus;
     if (in_array($paymentStatus, array('Completed', 'Pending', 'Processed', 'Failed', 'Reversed', 'Refunded', 'Partially-Refunded', 'Canceled_Reversal'))) {
         if (in_array($paymentStatus, array('Completed', 'Reversed', 'Refunded', 'Partially-Refunded', 'Canceled_Reversal'))) {
             $this->payment_date = gmdate('H:i:s M d, Y T', $paymentTime);
             // paypal-style
         }
         $this->payment_type = $paymentType;
     }
     if ($reasonCode) {
         $this->reason_code = $reasonCode;
     }
 }
	/**
	* Handles the gateway-specific result of payments (redirects back to this site and gateway notifications). WARNING: unchecked access !
	*
	* @param  cbpaidPaymentBasket  $paymentBasket         New empty object. returning: includes the id of the payment basket of this callback (strictly verified, otherwise untouched)
	* @param  array                $postdata              _POST data for saving edited tab content as generated with getEditTab
	* @param  boolean              $allowHumanHtmlOutput  Input+Output: set to FALSE if it's an IPN, and if it is already false, keep quiet
	* @return string                                      HTML to display if frontend, text to return to gateway if notification, FALSE if registration cancelled and ErrorMSG generated, or NULL if nothing to display
	*/
	public function resultNotification( $paymentBasket, $postdata, &$allowHumanHtmlOutput )
	{
		$ret = null;
		// $privateVarsList = 'id payment_method gateway_account user_id time_initiated time_completed ip_addresses mc_gross mc_currency quantity item_number item_name shared_secret payment_status';

		if ( cbGetParam( $_GET, 'result' ) == 'cancel') {
			
			// The user cancelled his payment (and registration):

			/* this check is done in cbpaidsubscription AFTER we return, as well as the updatePayment() call:
			$paymentBasketId				=	(int) $this->_getReqParam( 'basket' );
			if ( $paymentBasket->load( (int) $paymentBasketId ) ) {
				if ( $paymentBasket->payment_status == 'NotInitiated') {
			*/

			if ( $this->hashPdtBackCheck( $this->_getReqParam( 'pdtback', '' ) ) ) {
				$paymentBasketId				=	(int) $this->_getReqParam( 'basket' );
				$paymentBasket->id				=	$paymentBasketId;
				$paymentBasket->payment_status	=	'RegistrationCancelled';
				$this->_setErrorMSG(CBPTXT::T("Payment cancelled."));
				$ret = false;
			}
		}
		return  $ret;
	}
    case 'fixcbdb':
    case 'fixacldb':
    case 'fixcbmiscdb':
    case 'fixcbdeprecdb':
        TOOLBAR_usersextras::_TOOLS();
        break;
    case 'editPlugin':
        if (isset($_CB_Backend_Menu->mode)) {
            if (isset($_CB_Backend_Menu->menuItems) && $_CB_Backend_Menu->menuItems) {
                // Done above: TOOLBAR_usersextras::_PLUGIN_MENU( $_CB_Backend_Menu->menuItems );
            } elseif ($_CB_Backend_Menu->mode == 'show') {
                TOOLBAR_usersextras::_PLUGIN_ACTION_SHOW();
            } elseif ($_CB_Backend_Menu->mode == 'edit') {
                TOOLBAR_usersextras::_PLUGIN_ACTION_EDIT();
            }
        }
        break;
    case 'pluginmenu':
        $plugin = new PluginTable();
        $result = $plugin->load((int) cbGetParam($_REQUEST, 'pluginid', -1));
        if ($result) {
            $pluginMenuToolbarFile = $_CB_framework->getCfg('absolute_path') . '/' . $_PLUGINS->getPluginRelPath($plugin) . '/toolbar.' . $plugin->element . '.php';
            if (file_exists($pluginMenuToolbarFile)) {
                /** @noinspection PhpIncludeInspection */
                include_once $pluginMenuToolbarFile;
                break;
            }
        }
        TOOLBAR_usersextras::_DEFAULT_PLUGIN_MENU();
        break;
}
Beispiel #4
0
	function saveTab( $option ) {
		global $_CB_database, $_CB_framework, $_POST;

		$this->_importNeeded();
		$this->_importNeededSave();

		if ( isset( $_POST['params'] ) ) {
		 	$_POST['params']	=	cbParamsEditorController::getRawParamsMagicgpcEscaped( $_POST['params'] );
		} else {
			$_POST['params']	=	'';
		}
	
		if ( ! isset( $_POST['tabid'] ) || ( count( $_POST ) == 0 ) ) {
			echo "<script type=\"text/javascript\"> alert('" . addslashes( CBTxt::T('Missing post values') ) . "'); window.history.go(-2); </script>\n";
			exit();
		}
		if ( $_POST['tabid'] ) {
			$oldrow		=	new moscomprofilerTabs( $_CB_database );
			if ( $oldrow->load( (int) $_POST['tabid'] )
				&& 	( ! in_array( $oldrow->useraccessgroupid, getChildGIDS( userGID( $_CB_framework->myId() ) ) ) ) ) {
				echo "<script type=\"text/javascript\"> alert('" . addslashes( CBTxt::T('Unauthorized Access') ) . "'); window.history.go(-1);</script>\n";
				exit;
			}
		}
	
		$row = new moscomprofilerTabs( $_CB_database );
		if (!$row->bind( $_POST )) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
	
		if ( ! $row->ordering_register ) {
			$row->ordering_register		=	10;
		}
	
		$row->description	=	cleanEditorsTranslationJunk( trim( $row->description ) );
	
		if (!$row->check()) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
			exit();
		}
		$row->tabid			=	(int) cbGetParam( $_POST, 'tabid', 0 );
		if ( ! $row->store() ) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
			exit();
		}
	
		$row->checkin();
		cbRedirect( $_CB_framework->backendUrl( "index.php?option=$option&task=showTab" ), CBTxt::T('Successfully Saved Tab') . ": ". $row->title );
	}
 /**
  * Gives the URL of a link with plugin parameters.
  *
  * @param  array    $paramArray        array of string with key name of parameters
  * @param  string   $task              cb task to link to (default: userProfile)
  * @param  boolean  $sefed             TRUE to call cbSef (default), FALSE to leave URL unsefed
  * @param  array    $excludeParamList  of string with keys of parameters to not include
  * @param  string   $format            'html', 'raw'		(added in CB 1.2.3)
  * @return string                      value of the parameter (htmlspecialchared)
  */
 function _getAbsURLwithParam($paramArray, $task = 'userProfile', $sefed = true, $excludeParamList = null, $format = 'html')
 {
     global $_POST, $_GET;
     if ($excludeParamList === null) {
         $excludeParamList = array();
     }
     $prefix = $this->_getPrefix();
     if ($task == 'userProfile') {
         $Itemid = (int) getCBprofileItemid(0);
         unset($paramArray['Itemid']);
     } elseif (isset($paramArray['Itemid'])) {
         $Itemid = (int) $paramArray['Itemid'];
         unset($paramArray['Itemid']);
     } elseif (isset($_POST['Itemid'])) {
         $Itemid = (int) cbGetParam($_POST, 'Itemid', 0);
     } elseif (isset($_GET['Itemid'])) {
         $Itemid = (int) cbGetParam($_GET, 'Itemid', 0);
     } else {
         $Itemid = (int) getCBprofileItemid(0);
     }
     if ($task == 'userProfile' && !isset($paramArray['user'])) {
         if (isset($_POST['user'])) {
             $paramArray['user'] = urldecode(cbGetParam($_POST, 'user', null));
         } else {
             $paramArray['user'] = urldecode(cbGetParam($_GET, 'user', null));
         }
     }
     if ($task == 'pluginclass') {
         $plugin = $this->getPluginObject();
         $unsecureChars = array('/', '\\', ':', ';', '{', '}', '(', ')', "\"", "'", '.', ',', "", ' ', "\t", "\n", "\r", "\v");
         $paramArray['plugin'] = substr(str_replace($unsecureChars, '', $plugin->element), 0, 32);
         $paramArray['tab'] = null;
     } elseif (strtolower($task) == 'manageconnections') {
         $paramArray['plugin'] = null;
         $paramArray['tab'] = null;
     } else {
         $paramArray['plugin'] = null;
         if (!isset($paramArray['tab'])) {
             $paramArray['tab'] = strtolower(get_class($this));
         }
     }
     $uri = 'index.php?option=com_comprofiler&amp;task=' . $task . (isset($paramArray['user']) && $paramArray['user'] ? '&amp;user='******'user'])) : '') . ($Itemid ? '&amp;Itemid=' . $Itemid : '') . ($paramArray['tab'] ? '&amp;tab=' . htmlspecialchars(stripslashes($paramArray['tab'])) : '') . ($paramArray['plugin'] ? '&amp;plugin=' . htmlspecialchars(stripslashes($paramArray['plugin'])) : '');
     reset($paramArray);
     while (list($key, $val) = each($paramArray)) {
         if (!in_array($key, array('Itemid', 'user', 'tab', 'plugin')) && !in_array($key, $excludeParamList)) {
             if ($val) {
                 $uri .= '&amp;' . htmlspecialchars($prefix . $key) . '=' . htmlspecialchars(stripslashes($val));
             }
         }
     }
     if ($sefed) {
         return cbSef($uri, true, $format);
     } else {
         return $uri;
     }
 }
	/**
	 * USED by XML interface ONLY !!! Renders invoice
	 *
	 * @param  string           $value
	 * @param  ParamsInterface  $params
	 * @return string                    HTML to display
	 */
	public function renderInvoice( $value, &$params ) {
		global $_CB_framework;

		if ( ( $_CB_framework->getUi() == 2 ) && ( $_CB_framework->myId() != 0 ) ) {

			if ( cbpaidApp::getBaseClass() === null ) {
				//TODO: check if this is even needed:
				$pseudoPlugin				=	new getcbpaidsubscriptionsTab();
				$pseudoPlugin->params		=&	$params;
				cbpaidApp::getBaseClass( $pseudoPlugin );
			}
			$baseClass						=&	cbpaidApp::getBaseClass();

			$itsmyself					=	true;			// simulate user's view of invoice.

			$baseClass->outputRegTemplate();

			if ( strpos( cbGetParam( $_GET, 'invoice' ), ',') === false ) {
				if ( $this->load( (int) $value ) ) {
					$user					=	CBuser::getUserDataInstance( (int) $this->user_id );
				}
				return $this->displayInvoice( $user, $itsmyself, true );
			} else {
				$html					=	'<div class="cbregmultipage">';
				foreach ( explode( ',', cbGetParam( $_GET, 'invoice' ) ) as $basketId ) {
					$paymentBasket		=	new self();
					if ( $paymentBasket->load( (int) $basketId ) ) {
						$user			=	CBuser::getUserDataInstance( (int) $paymentBasket->user_id );
					}
					$html				.=	$paymentBasket->displayInvoice( $user, $itsmyself, false )
						.	'<hr class="cbregpagebreak" />';
					if ( is_callable( array( 'CBuser', 'unsetUsersNotNeeded' ) ) ) {
						// CB 1.8+:
						CBuser::unsetUsersNotNeeded( array( (int) $paymentBasket->user_id ) );
					}
					unset( $paymentBasket, $user );
				}
				$html					.=	'</div>';
			}
			return $html;
		}
		return null;
	}
	/**
	 * Logs notification
	 *
	 * @param  string                           $log_type
	 * @param  int                              $now
	 * @param  cbpaidPaymentBasket              $paymentBasket
	 * @return cbpaidPaymentNotification
	 */
	private function _logNotification( $log_type, $now, $paymentBasket )
	{
		global $_CB_database;

		$ipn = new cbpaidPaymentNotification($_CB_database);
		$ipn->payment_method	=	$this->getPayName();
		$ipn->gateway_account	=	$this->getAccountParam( 'id' );
		$ipn->log_type			=	$log_type;
		$ipn->time_received		=	date( 'Y-m-d H:i:s', $now );
		$ipn->payment_basket_id	=	$paymentBasket->id;

		$ipn->raw_data			=	'$_POST=' . var_export( $_POST, true ) . ';\n';

		$ipn->raw_result 		=	'FREE_TRIAL';
		$ipn->ip_addresses		=	cbpaidRequest::getIPlist();
		$ipn->notify_version	=	'2.1';
		$ipn->user_id			=	(int) cbGetParam( $_GET, 'user', 0 );
		$ipn->charset			=	'utf-8';
		$ipn->test_ipn			=	0;
		$ipn->first_name		=	$paymentBasket->first_name;
		$ipn->last_name			=	$paymentBasket->last_name;
		$ipn->payer_status		=	'unverified';
		$ipn->item_name			=	$paymentBasket->item_name;
		$ipn->item_number		=	$paymentBasket->item_number;
		$ipn->quantity			=	$paymentBasket->quantity;
		$ipn->custom			=	$paymentBasket->id;
		$ipn->invoice			=	$paymentBasket->invoice;
		$ipn->mc_currency		=	$paymentBasket->mc_currency;
		$ipn->tax				=	'0.00';
		$ipn->mc_gross			=	'0.00';
		$ipn->payment_status	=	'Completed';
		$ipn->payment_date		=	date( 'H:i:s M d, Y T', $now );			// paypal-style
		$ipn->payment_type		=	'Free trial';
		$ipn->txn_id			=	null;
		$ipn->txn_type			=	'web_accept';
		$ipn->recurring			=	0;

		$_CB_database->insertObject( $ipn->getTableName(), $ipn, $ipn->getKeyName() );

		return $ipn;
	}
	private function getGroups( $field, $postdata ) {
		$value			=	cbGetParam( $postdata, $field->name, null, _CB_ALLOWRAW );

		if ( is_array( $value ) ) {
			if ( $value ) foreach ( $value as $k => $v ) {
				if ( ( $v === null ) || ( $v === '' ) ) {
					unset( $value[$k] );
				}
			}

			if ( count( $value ) > 0 ) {
				cbArrayToInts( $value );

				$value	=	$this->_implodeCBvalues( $value );
			} else {
				$value	=	'';
			}
		} elseif ( ( $value === null ) || ( $value === '' ) ) {
			$value		=	'';
		} else {
			$value		=	(int) $value;
		}

		return $value;
	}
	/**
	 * Direct access to field for custom operations, like for Ajax
	 *
	 * WARNING: direct unchecked access, except if $user is set, then check well for the $reason ...
	 *
	 * @param  FieldTable  $field
	 * @param  UserTable    $user
	 * @param  array                 $postdata
	 * @param  string                $reason     'profile' for user profile view, 'edit' for profile edit, 'register' for registration, 'search' for searches
	 * @return string                            Expected output.
	 */
	public function getAjaxResponse( &$field, &$user, &$postdata, $reason )
	{
		global $_CB_framework, $_CB_database, $_PLUGINS, $ueConfig;

		if ( ( cbGetParam( $_GET, 'function', null ) == 'savevalue' ) && $this->canAjax( $field, $user, 'html', $reason, true ) ) {
			$field->set( '_noAjax', true );

			if ( in_array( $field->get( 'name' ), array ( 'firstname', 'middlename', 'lastname' ) ) ) {
				if ( $field->get( 'name' ) != 'firstname' ) {
					$postdata['firstname']			=	$user->get( 'firstname' );
				}

				if ( $field->get( 'name' ) != 'middlename' ) {
					$postdata['middlename']			=	$user->get( 'middlename' );
				}

				if ( $field->get( 'name' ) != 'lastname' ) {
					$postdata['lastname']			=	$user->get( 'lastname' );
				}
			}

			$_PLUGINS->callField( $field->get( 'type' ), 'fieldClass', array( &$field, &$user, &$postdata, $reason ), $field );

			$oldUserComplete						=	new UserTable( $_CB_database );

			foreach ( array_keys( get_object_vars( $user ) ) as $k ) {
				if ( substr( $k, 0, 1 ) != '_' ) {
					$oldUserComplete->set( $k, $user->get( $k ) );
				}
			}

			$orgValue								=	$user->get( $field->get( 'name' ) );

			$_PLUGINS->callField( $field->get( 'type' ), 'prepareFieldDataSave', array( &$field, &$user, &$postdata, $reason ), $field );

			$store									=	false;

			if ( ! count( $_PLUGINS->getErrorMSG( false ) ) ) {
				$_PLUGINS->callField( $field->get( 'type' ), 'commitFieldDataSave', array( &$field, &$user, &$postdata, $reason ), $field );

				if ( ! count( $_PLUGINS->getErrorMSG( false ) ) ) {
					if ( $_CB_framework->myId() == $user->get( 'id' ) ) {
						$user->set( 'lastupdatedate', $_CB_framework->getUTCDate() );
					}

					$_PLUGINS->trigger( 'onBeforeUserUpdate', array( &$user, &$user, &$oldUserComplete, &$oldUserComplete ) );

					$clearTextPassword				=	null;

					if ( $field->get( 'name' ) == 'password' ) {
						$clearTextPassword			=	$user->get( 'password' );

						$user->set( 'password', $user->hashAndSaltPassword( $clearTextPassword ) );
					}

					$store							=	$user->store();

					if ( $clearTextPassword ) {
						$user->set( 'password', $clearTextPassword );
					}

					$_PLUGINS->trigger( 'onAfterUserUpdate', array( &$user, &$user, $oldUserComplete ) );
				} else {
					$_PLUGINS->callField( $field->get( 'type' ), 'rollbackFieldDataSave', array( &$field, &$user, &$postdata, $reason ), $field );
					$_PLUGINS->trigger( 'onSaveUserError', array( &$user, $user->getError(), $reason ) );
				}
			}

			if ( ! $store ) {
				if ( $orgValue != $user->get( $field->get( 'name' ) ) ) {
					$user->set( $field->get( 'name' ), $orgValue );
				}
			}

			$return									=	null;

			switch ( $field->get( 'type' ) ) {
				case 'emailaddress';
					$value							=	$user->get( $field->get( 'name' ) );

					if ( $value ) {
						if ( $ueConfig['allow_email'] == 1 ) {
							$return					.=	'<a href="mailto:' . htmlspecialchars( $value ) . '"  target="_blank">' . htmlspecialchars( $value ) . '</a>';
						} else {
							$return					.=	htmlspecialchars( $value );
						}
					}
					break;
				case 'primaryemailaddress';
					$value							=	$user->get( $field->get( 'name' ) );

					if ( $value && ( $ueConfig['allow_email_display'] != 4 ) ) {
						switch ( $ueConfig['allow_email_display'] ) {
							case 1:
								$return				.=	htmlspecialchars( $value );
								break;
							case 2:
								$return				.=	'<a href="mailto:' . htmlspecialchars( $value ) . '">' . htmlspecialchars( $value ) . '</a>';
								break;
							case 3:
								$return				.=	'<a href="' . $_CB_framework->viewUrl( 'emailuser', true, array( 'uid' => (int) $user->get( 'id' ) ) ) . '" title="' . htmlspecialchars( CBTxt::T( 'UE_MENU_SENDUSEREMAIL_DESC', 'Send an Email to this user' ) ) . '">' . CBTxt::T( 'UE_SENDEMAIL', 'Send Email' ) . '</a>';
								break;
						}
					}
					break;
				default:
					$return							.=	$_PLUGINS->callField( $field->get( 'type' ), 'getFieldRow', array( &$field, &$user, 'html', 'none', $reason, 0 ), $field );
					break;
			}

			$placeholder							=	cbReplaceVars( CBTxt::T( $field->params->get( 'ajax_placeholder' ) ), $user );
			$emptyValue								=	cbReplaceVars( $ueConfig['emptyFieldsText'], $user );

			if ( ( ( ! $return ) || ( $return == $emptyValue ) ) && $placeholder ) {
				$return								=	$placeholder;
			} elseif ( ( ! $return ) && ( ! $ueConfig['showEmptyFields'] ) ) {
				$return								=	$emptyValue;
			}

			$error									=	$this->getFieldAjaxError( $field, $user, $reason );
			$return									=	( $error ? '<div class="alert alert-danger">' . $error . '</div>' : null ) . $return;

			$field->set( '_noAjax', false );

			return $return;
		}

		return null;
	}
Beispiel #10
0
	/**
	 * gets cookie set by cbSetcookie ! WARNING: always unescaped
	 * //TBD: add domain info in cookie-name
	 *
	 * @param  string            $name
	 * @param  string|array      $defaultValue
	 * @return string|array|null
	 */
	function getcookie( $name, $defaultValue = null ) {
		global $_COOKIE;
	
		return cbStripslashes( cbGetParam( $_COOKIE, $name, $defaultValue ) );
	}
Beispiel #11
0
 /**
  * Direct access to field for custom operations, like for Ajax
  *
  * WARNING: direct unchecked access, except if $user is set, then check well for the $reason ...
  *
  * @param  FieldTable  $field
  * @param  UserTable   $user
  * @param  array       $postdata
  * @param  string      $reason     'profile' for user profile view, 'edit' for profile edit, 'register' for registration, 'search' for searches
  * @return string                  Expected output.
  */
 public function fieldClass(&$field, &$user, &$postdata, $reason)
 {
     global $_CB_framework, $_CB_database, $_PLUGINS;
     parent::fieldClass($field, $user, $postdata, $reason);
     // Performs spoof check
     $myId = (int) $_CB_framework->myId();
     $userId = (int) $user->get('id');
     $fieldId = (int) $field->get('fieldid');
     $ipAddresses = cbGetIParray();
     $ipAddress = trim(array_shift($ipAddresses));
     $fieldName = $field->get('name');
     $readOnly = $this->_isReadOnly($field, $user, $reason);
     if (cbGetParam($_GET, 'function', null) == 'savevalue' && (!$readOnly && $this->getIncrementAccess($field, $user)) && $userId) {
         $oldUserComplete = new UserTable($field->getDbo());
         foreach (array_keys(get_object_vars($user)) as $k) {
             if (substr($k, 0, 1) != '_') {
                 $oldUserComplete->set($k, $user->get($k));
             }
         }
         $direction = stripslashes(cbGetParam($postdata, 'value'));
         $value = (int) $user->get($fieldName);
         if ($direction == 'plus') {
             $increment = (int) $field->params->get('points_inc_plus', 1);
             $value += $increment && $increment > 0 ? $increment : 0;
         } elseif ($direction == 'minus') {
             $increment = (int) $field->params->get('points_inc_minus', 1);
             $value -= $increment && $increment > 0 ? $increment : 0;
             $increment = $increment ? -$increment : 0;
         } else {
             $increment = 0;
         }
         $postdata[$fieldName] = $value;
         if ($this->validate($field, $user, $fieldName, $value, $postdata, $reason) && $increment && (int) $user->get($fieldName) != $value) {
             $query = 'INSERT INTO ' . $_CB_database->NameQuote('#__comprofiler_ratings') . "\n (" . $_CB_database->NameQuote('user_id') . ', ' . $_CB_database->NameQuote('type') . ', ' . $_CB_database->NameQuote('item') . ', ' . $_CB_database->NameQuote('target') . ', ' . $_CB_database->NameQuote('rating') . ', ' . $_CB_database->NameQuote('ip_address') . ', ' . $_CB_database->NameQuote('date') . ')' . "\n VALUES (" . $myId . ', ' . $_CB_database->Quote('field') . ', ' . $fieldId . ', ' . $userId . ', ' . (double) $increment . ', ' . $_CB_database->Quote($ipAddress) . ', ' . $_CB_database->Quote($_CB_framework->getUTCDate()) . ')';
             $_CB_database->setQuery($query);
             $_CB_database->query();
             $user->set($fieldName, (int) $value);
             $_PLUGINS->trigger('onBeforeUserUpdate', array(&$user, &$user, &$oldUserComplete, &$oldUserComplete));
             $query = 'UPDATE ' . $_CB_database->NameQuote('#__comprofiler') . "\n SET " . $_CB_database->NameQuote($fieldName) . " = " . (int) $user->get($fieldName) . "\n WHERE " . $_CB_database->NameQuote('id') . " = " . $userId;
             $_CB_database->setQuery($query);
             if ($_CB_database->query()) {
                 $_PLUGINS->trigger('onAfterUserUpdate', array(&$user, &$user, $oldUserComplete));
             }
         }
     }
     return $this->getPointsHTML($field, $user, $reason, true);
 }
	/**
	 * Validates saving permissions of $postArray depending on $params
	 * Temporary hack!
	 *
	 * @param  RegistryEditController  $params     The params editor
	 * @param  array                     $postArray  The array received from a POST of the form
	 * @return boolean|string
	 */
	public static function validateAndBindPost( $params, &$postArray ) {
		if ( count( $postArray ) ) {
			// Special handling for <param type="permissions"> fields:
			$xmls	=	$params->_xml->xpath( 'descendant::param[@type="permissions"]' );
			if ( count( $xmls ) > 0 ) {
				/** @var $node SimpleXMLElement */
				foreach ( $xmls as $node ) {
					if ( isset( $postArray[$node->attributes( 'name' )] ) ) {
						$rules	=	self::_save_permissions( $node->attributes( 'name' ), $postArray[$node->attributes( 'name' )], $node, '' );
						if ( is_object( $rules ) ) {
							// let's save the JSON string for future use:
							$postArray[$node->attributes( 'name' )]	=	(string) $rules;
						} elseif ( is_string( $rules ) ) {
							return $rules;
						}
					}
				}
			}
			// Special handling for <param onsave="class::method" key="firstparam" nosave="true"
			$xmls	=	$params->_xml->xpath( 'descendant::param[@onsave]' );
			if ( count( $xmls ) > 0 ) {
				foreach ( $xmls as $node ) {
					if ( isset( $postArray[$node->attributes( 'name' )] ) ) {

						// Call static method of class with first attribute key, and second the value:
						$classFunction	=	explode( '::', $node->attributes( 'onsave' ) );
						$key			=	$node->attributes( 'key' );
						if ( $classFunction && $key ) {
							call_user_func_array( $classFunction, array( $key, cbGetParam( $postArray, $node->attributes( 'name' ) ) ) );
						}

						// Unset the posted variable if nosave="true":
						if ( $node->attributes( 'nosave' ) == 'true' ) {
							unset( $postArray[$node->attributes( 'name' )] );
						}
					}
				}
			}
		}
		return true;
	}
Beispiel #13
0
/**
 * @param string $option
 */
function saveRegistrationNOCHECKSLOL($option)
{
    global $_CB_framework, $_CB_database, $ueConfig, $_POST, $_PLUGINS;
    // Check rights to access:
    if ($_CB_framework->getCfg('allowUserRegistration') == '0' && (!isset($ueConfig['reg_admin_allowcbregistration']) || $ueConfig['reg_admin_allowcbregistration'] != '1') || $_CB_framework->myId()) {
        cbNotAuth();
        return;
    }
    if (!isset($ueConfig['emailpass'])) {
        $ueConfig['emailpass'] = '******';
    }
    $userComplete = new moscomprofilerUser($_CB_database);
    // Pre-registration trigger:
    $_PLUGINS->loadPluginGroup('user');
    $_PLUGINS->trigger('onStartSaveUserRegistration', array());
    if ($_PLUGINS->is_errors()) {
        echo "<script type=\"text/javascript\">alert('" . addslashes($_PLUGINS->getErrorMSG()) . "'); </script>\n";
        $oldUserComplete = new moscomprofilerUser($_CB_database);
        $userComplete->bindSafely($_POST, $_CB_framework->getUi(), 'register', $oldUserComplete);
        HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, $_PLUGINS->getErrorMSG("<br />"));
        return;
    }
    // Check if this user already registered with exactly this username and password:
    $username = cbGetParam($_POST, 'username', '');
    $usernameExists = $userComplete->loadByUsername($username);
    if ($usernameExists) {
        $password = cbGetParam($_POST, 'password', '', _CB_ALLOWRAW);
        if ($userComplete->verifyPassword($password)) {
            $pwd_md5 = $userComplete->password;
            $userComplete->password = $password;
            $messagesToUser = activateUser($userComplete, 1, 'SameUserRegistrationAgain');
            $userComplete->password = $pwd_md5;
            echo "\n<div>" . implode("</div>\n<div>", $messagesToUser) . "</div>\n";
            return;
        } else {
            $msg = sprintf(_UE_USERNAME_ALREADY_EXISTS, $username);
            echo "<script type=\"text/javascript\">alert('" . addslashes($msg) . "'); </script>\n";
            $oldUserComplete = new moscomprofilerUser($_CB_database);
            $userComplete->bindSafely($_POST, $_CB_framework->getUi(), 'register', $oldUserComplete);
            HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, htmlspecialchars($msg));
            return;
        }
    }
    // Store and check terms and conditions accepted (not a field yet !!!!):
    if (isset($_POST['acceptedterms'])) {
        $userComplete->acceptedterms = (int) cbGetParam($_POST, 'acceptedterms', 0) == 1 ? 1 : 0;
    } else {
        $userComplete->acceptedterms = null;
    }
    if ($ueConfig['reg_enable_toc']) {
        if ($userComplete->acceptedterms != 1) {
            echo "<script type=\"text/javascript\">alert('" . addslashes(cbUnHtmlspecialchars(_UE_TOC_REQUIRED)) . "'); </script>\n";
            $oldUserComplete = new moscomprofilerUser($_CB_database);
            $userComplete->bindSafely($_POST, $_CB_framework->getUi(), 'register', $oldUserComplete);
            HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, _UE_TOC_REQUIRED . '<br />');
            return;
        }
    }
    // Set id to 0 for autoincrement and store IP address used for registration:
    $userComplete->id = 0;
    $userComplete->registeripaddr = cbGetIPlist();
    // Store new user state:
    $saveResult = $userComplete->saveSafely($_POST, $_CB_framework->getUi(), 'register');
    if ($saveResult === false) {
        echo "<script type=\"text/javascript\">alert('" . str_replace('\\\\n', '\\n', addslashes(strip_tags(str_replace('<br />', '\\n', $userComplete->getError())))) . "'); </script>\n";
        HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, $userComplete->getError());
        return;
    }
    if ($saveResult['ok'] === true) {
        $messagesToUser = activateUser($userComplete, 1, "UserRegistration");
    }
    foreach ($saveResult['tabs'] as $res) {
        if ($res) {
            $messagesToUser[] = $res;
        }
    }
    if ($saveResult['ok'] === false) {
        echo "<script type=\"text/javascript\">alert('" . str_replace('\\\\n', '\\n', addslashes(strip_tags(str_replace('<br />', '\\n', $userComplete->getError())))) . "'); </script>\n";
        HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, $userComplete->getError());
        return;
    }
    $_PLUGINS->trigger('onAfterUserRegistrationMailsSent', array(&$userComplete, &$userComplete, &$messagesToUser, $ueConfig['reg_confirmation'], $ueConfig['reg_admin_approval'], true));
    foreach ($saveResult['after'] as $res) {
        if ($res) {
            echo "\n<div>" . $res . "</div>\n";
        }
    }
    if ($_PLUGINS->is_errors()) {
        echo $_PLUGINS->getErrorMSG();
        HTML_comprofiler::registerForm($option, $ueConfig['emailpass'], $userComplete, $_POST, $_PLUGINS->getErrorMSG());
        return;
    }
    echo "\n<div>" . implode("</div>\n<div>", $messagesToUser) . "</div>\n";
}
	/**
	 * 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;
	}
 /**
  * Update all field values for a given $fieldId to match $fieldValues[]
  *
  * @param  int    $fieldId      Id of field
  * @param  array  $fieldValues  New or existing values: ordered array( array( 'fieldtitle' => 'Title of field', 'fieldlabel' => 'Label of field' ) )
  * @return boolean              Result
  */
 public function updateFieldValues($fieldId, array $fieldValues)
 {
     $existingFieldValues = $this->getFieldValuesOfField($fieldId);
     if ($fieldValues) {
         // Remove deleted field values:
         foreach ($existingFieldValues as $i => $existingFieldValue) {
             $i = (int) $i;
             $exists = false;
             foreach ($fieldValues as $fieldValue) {
                 $fieldValue = (array) $fieldValue;
                 $id = (int) cbGetParam($fieldValue, 'fieldvalueid');
                 //TODO: Use new Input class
                 $title = trim(stripslashes(cbGetParam($fieldValue, 'fieldtitle')));
                 if ($id && $i == $id && $title != '') {
                     $exists = true;
                     break;
                 }
             }
             if (!$exists) {
                 if (!$this->delete($i)) {
                     return false;
                 }
                 unset($existingFieldValues[$i]);
             }
         }
         // Insert new field values or update existing:
         foreach ($fieldValues as $i => $fieldValue) {
             $fieldValue = (array) $fieldValue;
             $id = (int) cbGetParam($fieldValue, 'fieldvalueid');
             //TODO: Use new Input class
             $title = trim(stripslashes(cbGetParam($fieldValue, 'fieldtitle')));
             $label = trim(stripslashes(cbGetParam($fieldValue, 'fieldlabel')));
             if ($title != '') {
                 if (isset($existingFieldValues[$id])) {
                     $newFieldValue = $existingFieldValues[$id];
                     if ((int) $newFieldValue->get('fieldid') == (int) $fieldId && $newFieldValue->get('fieldtitle') == $title && $newFieldValue->get('fieldlabel') == $label && (int) $newFieldValue->get('ordering') == (int) ($i + 1)) {
                         continue;
                     }
                 } else {
                     $newFieldValue = new FieldValueTable($this->_db);
                 }
                 $newFieldValue->set('fieldid', (int) $fieldId);
                 $newFieldValue->set('fieldtitle', $title);
                 $newFieldValue->set('fieldlabel', $label);
                 $newFieldValue->set('ordering', (int) ($i + 1));
                 if (!$newFieldValue->store()) {
                     return false;
                 }
             }
         }
         $this->updateOrder($this->_db->NameQuote('fieldid') . " = " . (int) $fieldId);
     } else {
         // Delete all current field values:
         $query = 'DELETE' . "\n FROM " . $this->_db->NameQuote($this->_tbl) . "\n WHERE " . $this->_db->NameQuote('fieldid') . " = " . (int) $fieldId;
         $this->_db->setQuery($query);
         if (!$this->_db->query()) {
             return false;
         }
     }
     return true;
 }
Beispiel #16
0
	/**
	 * @param FieldTable $field
	 * @param UserTable  $user
	 * @param array      $postdata
	 * @param bool       $joined
	 * @return null|string
	 */
	private function getValue( $field, $user, $postdata, $joined = false )
	{
		$value						=	cbGetParam( $postdata, $field->get( 'name' ), null, _CB_ALLOWRAW );

		if ( ( $value === null ) || ( $value === '' ) || ( is_array( $value ) && ( count( $value ) <= 0 ) ) ) {
			$value					=	'';
		} else {
			$options				=	$this->getGroups( $field, $user, true, $joined );
			$groups					=	array();

			foreach ( $options as $option ) {
				$groups[]			=	$option->value;
			}

			if ( is_array( $value ) ) {
				$values				=	array();

				foreach ( $value as $k => $v ) {
					$v				=	stripslashes( $v );

					if ( in_array( $value, $groups ) ) {
						$values[]	=	$v;
					}
				}

				$value				=	$this->_implodeCBvalues( $values );
			} else {
				$value				=	stripslashes( $value );

				if ( ! in_array( $value, $groups ) ) {
					$value			=	null;
				}
			}
		}

		return $value;
	}
 /**
  * Gets a cleaned value from a PHP global
  *
  * @param  string $arn
  * @param  string $name
  * @param  mixed  $def
  * @return mixed
  */
 protected static function _globalConv($arn, $name, $def = null)
 {
     switch ($arn) {
         case 'request':
             global $_REQUEST;
             $value = cbGetParam($_REQUEST, $name, $def);
             break;
         case 'get':
             global $_GET;
             $value = cbGetParam($_GET, $name, $def);
             break;
         case 'post':
             global $_POST;
             $value = cbGetParam($_POST, $name, $def);
             break;
         case 'cookie':
             global $_COOKIE;
             $value = cbGetParam($_COOKIE, $name, $def);
             break;
         case 'cbcookie':
             cbimport('cb.session');
             $value = CBCookie::getcookie($name, $def);
             break;
         case 'session':
             global $_SESSION;
             $value = cbGetParam($_SESSION, $name, $def);
             break;
         case 'server':
             global $_SERVER;
             $value = cbGetParam($_SERVER, $name, $def);
             break;
         case 'env':
             global $_ENV;
             $value = cbGetParam($_ENV, $name, $def);
             break;
         default:
             trigger_error(sprintf('SQLXML::globalconv error: unknown type %s for %s.', $arn, $name), E_USER_NOTICE);
             $value = null;
             break;
     }
     return stripslashes($value);
 }
	/**
	 * Checks ARB silent post hash
	 *
	 * @param  array  $postdata   $_POST data to check
	 * @return bool               TRUE: hash correct, FALSE: incorrect
	 */
	private function _checkHashARBsilent( $postdata )
	{
		$amount		=	sprintf( '%0.2f', (float) cbGetParam( $postdata, 'x_amount' ) );
		$transid	=	cbGetParam( $postdata, 'x_trans_id' );
		$hash		=	cbGetParam( $postdata, 'x_MD5_Hash' );
		$mdhash		=	$this->getAccountParam( 'authorize_md_hash', '' );
		return ( md5( $mdhash . $transid . $amount ) === strtolower( $hash ) );
	}
function tabClass($option, $task, $uid)
{
    global $_PLUGINS, $_REQUEST, $_POST;
    if ($uid) {
        $cbUser =& CBuser::getInstance((int) $uid);
        if ($cbUser) {
            $user =& $cbUser->getUserData();
        } else {
            $cbUser =& CBuser::getInstance(null);
            $user = null;
        }
    } else {
        $cbUser =& CBuser::getInstance(null);
        $user = null;
    }
    $unsecureChars = array('/', '\\', ':', ';', '{', '}', '(', ')', "\"", "'", '.', ',', "", ' ', "\t", "\n", "\r", "\v");
    if ($task == 'fieldclass') {
        if ($user && $user->id) {
            $uid = $user->id;
        } else {
            $uid = 0;
        }
        $msg = checkCBpermissions(array($uid), "edit", true);
        $_PLUGINS->trigger('onBeforeUserProfileEditRequest', array($uid, &$msg, 2));
        if ($msg) {
            echo $msg;
            return;
        }
        $fieldName = trim(substr(str_replace($unsecureChars, '', urldecode(stripslashes(cbGetParam($_REQUEST, "field")))), 0, 50));
        if (!$fieldName) {
            echo CBTxt::T('no field');
            return;
        }
        $pluginName = null;
        $tabClassName = null;
        $method = null;
    } elseif ($task == 'tabclass') {
        $tabClassName = urldecode(stripslashes(cbGetParam($_REQUEST, "tab")));
        if (!$tabClassName) {
            return;
        }
        $pluginName = null;
        $tabClassName = substr(str_replace($unsecureChars, '', $tabClassName), 0, 32);
        $method = 'getTabComponent';
        $fieldName = null;
    } elseif ($task == 'pluginclass') {
        $pluginName = urldecode(stripslashes(cbGetParam($_REQUEST, "plugin")));
        if (!$pluginName) {
            return;
        }
        $tabClassName = 'CBplug_' . strtolower(substr(str_replace($unsecureChars, '', $pluginName), 0, 32));
        $method = 'getCBpluginComponent';
        $fieldName = null;
    } else {
        throw new LogicException('Unexpected task for CB tabClass');
    }
    $tabs = $cbUser->_getCbTabs(false);
    if ($task == 'fieldclass') {
        $result = $tabs->fieldCall($fieldName, $user, $_POST, 'edit');
    } else {
        $result = $tabs->tabClassPluginTabs($user, $_POST, $pluginName, $tabClassName, $method);
    }
    if ($result === false) {
        if ($_PLUGINS->is_errors()) {
            echo "<script type=\"text/javascript\">alert(\"" . $_PLUGINS->getErrorMSG() . "\"); </script>\n";
        }
    } elseif ($result !== null) {
        echo $result;
    }
}
 /**
  * Saves the registration tab/area postdata into the tab's permanent storage
  * @param  moscomprofilerTab   $tab       the tab database entry
  * @param  moscomprofilerUser  $user      the user being displayed
  * @param  int                 $ui        1 for front-end, 2 for back-end
  * @param  array               $postdata  _POST data for saving edited tab content as generated with getEditTab
  * @return mixed                          either string HTML for tab content, or false if ErrorMSG generated
  */
 function saveRegistrationTab($tab, &$user, $ui, $postdata)
 {
     global $ueConfig, $_CB_framework, $mainframe;
     // $mainframe needed by the require
     if (!$this->_CheckYancInstalled()) {
         return null;
     }
     $ret = null;
     if (true) {
         require_once $_CB_framework->getCfg('absolute_path') . _NEWSLETTERFILE;
         $newslettersSubscriptions = new YancSubscription();
         $lists = cbGetParam($postdata, 'newsLitems', array(0));
         $html = cbGetParam($postdata, 'newsLhtml', 1);
         $sendEmail = ($ueConfig['reg_confirmation'] != "1" and $ueConfig['reg_admin_approval'] != "1");
         // $result = $newslettersSubscriptions->saveMassSubscribe($user, $lists, $html, $sendEmail);
         foreach ($lists as $li) {
             $result = $newslettersSubscriptions->saveSubscription($user, $li, $html, $sendEmail);
             if ($result !== true) {
                 $this->_setErrorMSG($result);
                 $ret = false;
             }
         }
     }
     return $ret;
 }
 /**
  * Saves legacy user edit display
  *
  * @param string $option
  * @param string $task
  */
 public function saveUser($option, $task = 'save')
 {
     global $_CB_framework, $_CB_Backend_task, $_POST, $_PLUGINS;
     cbimport('language.all');
     cbimport('cb.tabs');
     cbimport('cb.params');
     cbimport('cb.adminfilesystem');
     cbimport('cb.imgtoolbox');
     $userIdPosted = (int) cbGetParam($_POST, 'id', 0);
     if ($userIdPosted == 0) {
         $_POST['id'] = null;
     }
     $msg = $this->_authorizedEdit($userIdPosted);
     if (!$msg) {
         if ($userIdPosted != 0) {
             $msg = checkCBpermissions(array($userIdPosted), 'save', true);
         } else {
             $msg = checkCBpermissions(null, 'save', true);
         }
     }
     if ($userIdPosted != 0) {
         $_PLUGINS->trigger('onBeforeUserProfileSaveRequest', array($userIdPosted, &$msg, 2));
     }
     if ($msg) {
         cbRedirect($_CB_framework->backendViewUrl('showusers', false), $msg, 'error');
     }
     $_PLUGINS->loadPluginGroup('user');
     // Get current user state:
     if ($userIdPosted != 0) {
         $userComplete = CBuser::getUserDataInstance($userIdPosted);
         if (!($userComplete && $userComplete->id)) {
             cbRedirect($_CB_framework->backendViewUrl('showusers', false), CBTxt::T('Your profile could not be updated.'), 'error');
         }
     } else {
         $userComplete = new UserTable();
     }
     // Store new user state:
     $saveResult = $userComplete->saveSafely($_POST, $_CB_framework->getUi(), 'edit');
     if (!$saveResult) {
         $regErrorMSG = $userComplete->getError();
         $msg = checkCBpermissions(array((int) $userComplete->id), 'edit', true);
         if ($userIdPosted != 0) {
             $_PLUGINS->trigger('onBeforeUserProfileEditRequest', array((int) $userComplete->id, &$msg, 2));
         }
         if ($msg) {
             cbRedirect($_CB_framework->backendViewUrl('showusers', false), $msg, 'error');
         }
         if ($userIdPosted != 0) {
             $_PLUGINS->trigger('onAfterUserProfileSaveFailed', array(&$userComplete, &$regErrorMSG, 2));
         } else {
             $_PLUGINS->trigger('onAfterUserRegistrationSaveFailed', array(&$userComplete, &$regErrorMSG, 2));
         }
         $_CB_framework->enqueueMessage($regErrorMSG, 'error');
         $_CB_Backend_task = 'edit';
         // so the toolbar comes up...
         $_PLUGINS->loadPluginGroup('user');
         // resets plugin errors
         $userView = _CBloadView('user');
         /** @var CBController_user $userView */
         $userView->edituser($userComplete, $option, $userComplete->user_id != null ? 0 : 1, $_POST);
         return;
     }
     // Checks-in the row:
     $userComplete->checkin();
     if ($userIdPosted != 0) {
         $_PLUGINS->trigger('onAfterUserProfileSaved', array(&$userComplete, 2));
     } else {
         $messagesToUser = array();
         $_PLUGINS->trigger('onAfterSaveUserRegistration', array(&$userComplete, &$messagesToUser, 2));
     }
     if ($task == 'apply') {
         cbRedirect($_CB_framework->backendViewUrl('edit', false, array('cid' => (int) $userComplete->user_id)), CBTxt::T('SUCCESSFULLY_SAVED_USER_USERNAME', 'Successfully Saved User: [username]', array('[username]' => $userComplete->username)));
     } else {
         cbRedirect($_CB_framework->backendViewUrl('showusers', false), CBTxt::T('SUCCESSFULLY_SAVED_USER_USERNAME', 'Successfully Saved User: [username]', array('[username]' => $userComplete->username)));
     }
 }
 /**
  * Checks messaging anti-spam
  *
  * @param  boolean      $autoBack     TRUE: returns code 403 and attempts a "back" in browser with Javascript, FALSE: Returns error text
  * @param  boolean      $allowPublic  TRUE: Also checks for guests, FALSE: Only for registered and logged-in users
  * @return null|string                NULL: Ok, String: translated error text
  */
 function cbAntiSpamCheck($autoBack = true, $allowPublic = false)
 {
     global $_POST;
     $validateValuePost = cbGetParam($_POST, 'cbvssps', '');
     cbimport('cb.session');
     $validateValueCookie = CBCookie::getcookie('cbvs');
     $parts0 = explode('_', $validateValuePost);
     $parts1 = explode('_', $validateValueCookie);
     $match = false;
     if (count($parts0) == 3 && count($parts1) == 3) {
         $validate = cbGetAntiSpams($parts0[2], $parts1[2], $allowPublic);
         $match = $validateValuePost === $validate[0] || $validateValueCookie === $validate[1];
     }
     if (!$match) {
         if ($autoBack) {
             _cbExpiredSessionJSterminate();
         } else {
             return CBTxt::Th('UE_SESSION_EXPIRED', 'Session expired or cookies are not enabled in your browser. Please press "reload page" in your browser, and enable cookies in your browser.') . ' ' . CBTxt::Th('UE_PLEASE_REFRESH', 'Please refresh/reload page before filling-in.');
         }
     }
     return null;
 }
	/**
	* gets the chosen plans from the form, and checks if they are allowed for that user
	* also gets the options of the plans
	* In detail:
	* gets an array of array of int as an array of int (removing first level), verifying that if index is not 0 the parent exists
	* In each plan object there is a ->_options variable with a Registry object with the option values of the plan
	*
	* @param  UserTable        $user            Reflecting the user being registered or saved
	* @param  string           $name            name of parameter in REQUEST URL
	* @param  cbpaidProduct[]  $allowedPlans    array of cbpaidProduct  which are allowed
	* @param  boolean          $isRegistration  TRUE: Registration process (guest), or FALSE: upgrade-process (logged-in user)
	* @param  string           $reason          Subscription reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
	* @param  boolean          $returnPlans     TRUE: returns plan objects or FALSE: returns plan ids only.
	* @param  string           $postfix         postfix for identifying multiple plans spaces (optional)
	* @return int[]|cbpaidProduct[]|string     ARRAY of int|of cbpaidProducts : Plans which are selected within hierarchy (according to the post, to be rechecked !) or STRING: error message.
	*/
	protected function & _planGetAndCheckReqParamArray( &$user, $name, &$allowedPlans, $isRegistration, $reason, $returnPlans = false, $postfix = '' ) {
		global $_CB_framework, $_POST;

		$params							=&	cbpaidApp::settingsParams();
		$enableFreeRegisteredUser		=	$params->get( 'enableFreeRegisteredUser', 1 );
		$createAlsoFreeSubscriptions	=	$params->get( 'createAlsoFreeSubscriptions', 0 );

		$ui								=	$_CB_framework->getUi();
		if ( ! $isRegistration ) {
			if ( $ui == 1 ) {
				$userId					=	(int) cbGetParam( $_POST, 'user', 0 );
			} else {
				$userId					=	(int) cbGetParam( $_POST, 'id', 0 );
			}
		} else {
			$userId						=	null;
		}

		$selectedPlanIds							=	$this->_plangetReqParamArray( $name, $postfix );
		/// $validSub									=	array();
		// 1. checks that selected plans hierarchy is respected:
		$ok											=	true;
		$plansMgr									=	null;
		foreach ( $selectedPlanIds as $id ) {
			if ( $id != 0 ) {						// ignore "None" plan in backend edit profile
				$ok									=	false;
	
				// foreach ( $allowedPlans as $planid => $p ) {
				if ( isset( $allowedPlans[(int) $id] ) ) {
					$p								=	$allowedPlans[(int) $id];
	
					if ( $id == $p->id ) {
						$parentOk					=	true;
						$parentId					=	$p->get( 'parent' );
						if ( $parentId != 0 ) {
							// the selected plan has a parent plan: check if parent plan is also chosen or already subscribed and active:
							$parentOk				=	false;
							foreach ($selectedPlanIds as $selPlanId ) {
								if ( $parentId == $selPlanId ) {
									$parentOk		=	true;
									break;
								}
							}
							if ( ( ! $isRegistration ) && ( ! $parentOk ) ) {
								// try to see if user is subscribed already to the parent plan:
								if ( $userId ) {
									if ( $plansMgr === null ) {
										$plansMgr	=&	cbpaidPlansMgr::getInstance();
									}
									$plan			=	$plansMgr->loadPlan( $parentId );
									/** @var $plan cbpaidProduct */
									if ( $plan ) {
										// Check if allow free lifetime users without need to create such subscriptions:
										if ( $enableFreeRegisteredUser && ( ! $createAlsoFreeSubscriptions ) && $plan->isLifetimeValidity() && $plan->isFree() ) {
											$parentOk		=	true;
										} else {
											$sub			=	$plan->newSubscription();
											/** @var $sub cbpaidSomething */
											if ( $sub->loadValidUserSubscription( $userId ) ) {
												$parentOk	=	true;
												/// $validSub[$parentId]		=	$sub->id;
											}
										}
									}
								}
							}
						}
						if ( $parentOk ) {
							$ok						=	true;
						}
						break;
					}
				}
				if ( ! $ok ) {
					break;
				}
			}
		}

		if ( ! $ok ) {
			$selectedPlanIds								=	CBPTXT::T("Chosen plans combination is not allowed (you must choose coherent plans selection, e.g. parent subscriptions to a plan must be active).");
		} else {
			// 2. Check that all exclusivities are respected:
			$plansMgr										=&	cbpaidPlansMgr::getInstance();
			// 2.a. build array of exclusive [parent][plan]:
			$exclusiveChildren								=	array();
			// 2.a.1. add the plans just selected now:
			foreach ($allowedPlans as $id => $p ) {
				if ( $p->get( 'exclusive' ) ) {
					$exclusiveChildren[$p->get( 'parent' )][$p->get( 'id' )]	=	( in_array( $id, $selectedPlanIds ) ? 1 : 0 );
				}
			}
			// 2.a.2. add the plans already subscribed with active subscription (if we are not just upgrading that level):
			$ValidUserPlans									=	array();
			$validSubExists									=	array();
			if ( ( ! $isRegistration ) && $userId ) {
				foreach ( $exclusiveChildren as $parentId => $exclPlansArray ) {
					if ( $parentId != 0 ) {
						$plan								=	$plansMgr->loadPlan( $parentId );
						if ( $plan ) {
							$sub							=	$plan->newSubscription();
							$ValidUserPlans[$parentId]		=	( $sub->loadValidUserSubscription( $userId ) );
						} else {
							$selectedPlanIds				=	CBPTXT::T("Chosen plan has a parent plan configured that doesn't exist anymore.");
						}
					}
					$numberOfSelected						=	array_sum( $exclPlansArray );
					if ( $numberOfSelected == 0 ) {
						$firstFreeLifeTime					=	array();
						// foreach ( $exclPlansArray as $childId => $selected )
						foreach ( array_keys( $exclPlansArray ) as $childId ) {
							$plan							=	$plansMgr->loadPlan( $childId );
							if ( ( ! isset( $firstFreeLifeTime[$parentId] ) ) && ( $enableFreeRegisteredUser && ( ! $createAlsoFreeSubscriptions ) && $plan->isLifetimeValidity() && $plan->isFree() ) ) {
								$firstFreeLifeTime[$parentId]	=	$plan->get( 'id' );
							}
							if ( ! isset( $ValidUserPlans[$childId] ) ) {
								$sub						=	$plan->newSubscription();
								$ValidUserPlans[$childId]	=	( $sub->loadValidUserSubscription( $userId ) );
							}
							if ( $ValidUserPlans[$childId] ) {
								$exclusiveChildren[$parentId][$childId]		=	1;
								$validSubExists[$parentId]						=	1;
							}
						}
					}
				}
			}
			// 2.b. check that exactly 1 exclusive plan is selected at each level (including still valid subscribed plans) which matters:
			if ( ! ( ( $ui == 2 ) && ( $selectedPlanIds == array( '0' ) ) ) ) {		// ignore "None" plan in backend edit profile
				foreach ( $exclusiveChildren as $parentId => $exclPlansArray ) {
					$numberOfSelected						=	array_sum( $exclPlansArray );
					if ( $numberOfSelected > 1 ) {
						$selectedPlanIds					=	CBPTXT::T("Chosen plans combination is not allowed (you can't choose more than one mandatory plan).") . $numberOfSelected;
						break;
					}
					elseif ( ( $numberOfSelected == 0 ) && ( ! isset( $validSubExists[$parentId] ) ) && ( ! isset( $firstFreeLifeTime[$parentId] ) ) ) {
						if ( ( $parentId == 0 ) || in_array( $parentId, $selectedPlanIds ) || ( isset( $ValidUserPlans[$parentId] ) && ( $ValidUserPlans[$parentId] == true ) ) )
						{
							$selectedPlanIds				=	CBPTXT::T("Chosen plans combination is not allowed (you must choose coherent plans selection, e.g. mandatory subscription(s) must be active or mandatory plan(s) must be chosen).");
							$names							=	array();
							foreach ( array_keys( $exclPlansArray ) as $childId ) {
								$exclPlan					=&	$plansMgr->loadPlan( $childId );
								/** @var $exclPlan cbpaidProduct */
								$names[]					=	$exclPlan->get( 'name' );
							}
							if ( $parentId ) {
								$parentPlan					=&	$plansMgr->loadPlan( $parentId );
								/** @var $parentPlan cbpaidProduct */
								$parentName					=	$parentPlan->get( 'name' );
								$selectedPlanIds			.=	' ' . CBPTXT::T( sprintf( "'%s' has mandatory options '%s' and none is selected." , $parentName, implode( "', '", $names ) ) );
							}
							break;
						}
					}
				}
			}
			// 3. Checks that all selected plans' conditions are met:
			if ( is_array( $selectedPlanIds ) ) {
				foreach ( $selectedPlanIds as $id ) {
					if ( $id ) {
						$plan								=&	$plansMgr->loadPlan( $id );
						if ( $plan ) {
							if ( ! $plan->checkActivateConditions( $user, $reason, $selectedPlanIds ) ) {
								// Error text will be in selectedPlanIds in case of error returning false:
								break;
							}
						}
					}
				}
			}
			// 4. Checks done:
			if ( $returnPlans && is_array( $selectedPlanIds ) && ( count( $selectedPlanIds ) > 0 ) ) {
				// if returning selected plans, sort them in same order and with same keys as corresponding allowed plans:
				global $_PLUGINS;
				$_PLUGINS->loadPluginGroup( 'user', 'cbsubs.' );
				$_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');

				$selectedPlans								=	array();
				foreach ($allowedPlans as $id => $p ) {
					if ( in_array( $id, $selectedPlanIds ) ) {
						/** @var cbpaidProduct[] $selectedPlans */
						$selectedPlans[(int) $id]			=	$allowedPlans[$id];
						$selectionId						=	'plan' . $id;
						$selectionName						=	'plan' . ( $selectedPlans[$id]->get( 'exclusive' ) ? 'E' : 'N' ) . '[' . (int) $selectedPlans[$id]->parent . ']';
						$selectionValue						=	$id;
						$view								=	$selectedPlans[$id]->getViewer();

						$paramsOrString						=	$view->getOptions( $selectionId, $selectionName, $selectionValue, $reason );
						if ( is_string( $paramsOrString ) ) {
							$selectedPlans					=	$paramsOrString;		// error message
							break;
						}
						$selectedPlans[(int) $id]->_options		=	$paramsOrString;
						$selectedPlans[(int) $id]->_integrations	=	new Registry( '' );
						$_PLUGINS->trigger( 'onCPayAfterPlanSelected', array( &$selectedPlans[(int) $id], &$selectedPlans[(int) $id]->_integrations , $reason ) );
						if ( $_PLUGINS->is_errors() ) {
							$selectedPlans							=	$_PLUGINS->getErrorMSG();
							break;
						}
					}
				}
				return $selectedPlans;
			}
		}
		return $selectedPlanIds;
	}
Beispiel #24
0
 /**
  * Gets html code for all cb tabs, sorted by position (default: all, no position name in db means "cb_tabmain")
  *
  * @param  UserTable  $user      CB user object to display
  * @param  string     $position  Name of position if only one position to display (default: null)
  * @return array                 Array of string with html to display at each position, key = position name, or NULL if position is empty.
  *
  * @throws \LogicException
  */
 public function getViewTabs($user, $position = '')
 {
     global $_CB_framework, $ueConfig;
     // returns cached rendering if needed:
     static $renderedCache = array();
     if (isset($renderedCache[$user->id])) {
         if ($position == '') {
             return $renderedCache[$user->id];
         }
         if (isset($renderedCache[$user->id][$position])) {
             return array($position => $renderedCache[$user->id][$position]);
         }
     }
     // detects recursion loops (e.g. trying to render a position within a position !):
     static $callCounter = 0;
     if ($callCounter++ > 10) {
         throw new \LogicException('Rendering recursion for CB position: ' . $position, 500);
     }
     // loads the tabs and generate the inside content of the tab:
     $this->generateViewTabsContent($user, $position);
     // recursion counter decrement:
     $callCounter--;
     if (!isset($this->tabsToDisplay[$position])) {
         return null;
     }
     //	$output									=	'html';
     $tabsMap = array();
     $html = array();
     $results = array();
     $oNest = array();
     $oNestVert = array();
     $oMenu = array();
     $oMenuNest = array();
     $oVert = array();
     $i = 0;
     //Pass 3: generate formatted output for each position by display type (keeping tabs together in each position)
     foreach ($this->tabsToDisplay[$position] as $k => $oTab) {
         if ($oTab->pluginclass) {
             $tabsMap[strtolower($oTab->pluginclass)] = $oTab->tabid;
         }
         $pos = $oTab->position;
         if (!isset($html[$pos])) {
             $html[$pos] = '';
             $results[$pos] = '';
             $oNest[$pos] = '';
             $oNestVert[$pos] = '';
             $oMenu[$pos] = '';
             $oMenuNest[$pos] = '';
             $oVert[$pos] = '';
         }
         // handles content of tab:
         $tabContent = $this->tabsContents[$k];
         if ($tabContent != '' || $oTab->fields && $oTab->_fieldsCount > 0 && isset($ueConfig['showEmptyTabs']) && $ueConfig['showEmptyTabs'] == 1) {
             $overlaysWidth = '400';
             //BB later this could be one more tab parameter...
             $tabTitle = $this->_callTabPlugin($oTab, $user, $oTab->pluginclass, 'getTabTitle', $oTab->pluginid);
             switch ($oTab->displaytype) {
                 //	case "template":
                 //		$cbTemplate	=	HTML_comprofiler::_cbTemplateLoad();
                 //		$html[$pos] .=	HTML_comprofiler::_cbTemplateRender( $cbTemplate, $user, 'Profile', 'drawTab', array( &$user, $oTab, $tabTitle, $tabContent, 'cb_tabid_' . $oTab->tabid ), $output );
                 //		break;
                 case "html":
                     $html[$pos] .= '<div class="cb_tab_content cb_tab_html' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '" id="cb_tabid_' . (int) $oTab->tabid . '">' . $tabContent . '</div>';
                     break;
                 case "div":
                     $html[$pos] .= '<div class="cb_tab_content cb_tab_div' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '" id="cb_tabid_' . (int) $oTab->tabid . '">' . '<div class="cb_tab_content_heading page-header"><h4>' . $tabTitle . '</h4></div>' . $tabContent . '</div>';
                     break;
                 case "rounddiv":
                     $html[$pos] .= '<div class="cb_tab_container cb_tab_rounddiv panel panel-default' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '">' . '<div class="panel-heading">' . $tabTitle . '</div>' . '<div class="cb_tab_content panel-body" id="cb_tabid_' . (int) $oTab->tabid . '">' . $tabContent . '</div>' . '</div>';
                     break;
                 case "roundhtml":
                     $html[$pos] .= '<div class="cb_tab_container cb_tab_roundhtml panel panel-default' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '">' . '<div class="cb_tab_content panel-body" id="cb_tabid_' . (int) $oTab->tabid . '">' . $tabContent . '</div>' . '</div>';
                     break;
                 case "overlib":
                     $fieldTip = '<div class="cb_tab_content cb_tab_overlib' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '" id="cb_tabid_' . (int) $oTab->tabid . '" style="width:100%">' . $tabContent . '</div>';
                     $html[$pos] .= cbTooltip($this->ui, $fieldTip, $tabTitle, $overlaysWidth, null, $tabTitle, null, 'data-cbtooltip-position-target="mouse" data-cbtooltip-tip-hide="true" class="cb_tab_overlib_container"');
                     break;
                 case "overlibfix":
                     $fieldTip = '<div class="cb_tab_content cb_tab_overlib_fix' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '" id="cb_tabid_' . (int) $oTab->tabid . '" style="width:100%">' . $tabContent . '</div>';
                     $html[$pos] .= cbTooltip($this->ui, $fieldTip, $tabTitle, $overlaysWidth, null, $tabTitle, null, 'data-cbtooltip-delay="200" class="cb_tab_overlib_fix_container"');
                     break;
                 case "overlibsticky":
                     $fieldTitle = '<button type="button" class="cb_tab_overlib_sticky_button btn btn-default">' . $tabTitle . '</button>';
                     $fieldTip = '<div class="cb_tab_content cb_tab_overlib_sticky' . ($oTab->cssclass ? ' ' . htmlspecialchars($oTab->cssclass) : null) . '" id="cb_tabid_' . (int) $oTab->tabid . '" style="width:100%">' . $tabContent . '</div>';
                     $html[$pos] .= cbTooltip($this->ui, $fieldTip, $tabTitle, $overlaysWidth, null, $fieldTitle, null, 'data-cbtooltip-open-event="click" data-cbtooltip-close-event="click unfocus" class="cb_tab_overlib_sticky_container"');
                     break;
                 case "nested":
                     $oNest[$pos] .= $this->startTab('CBNested' . $pos, $tabTitle, $oTab->tabid, array('tab' => 'cbTabNavNested' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'pane' => 'cbTabPaneNested' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null))) . '<div class="cb_tab_content cb_tab_nested" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
                 case "nestedvertical":
                     $oNestVert[$pos] .= $this->startTab('CBNestedVertical' . $pos, $tabTitle, $oTab->tabid, array('tab' => 'cbTabNavNestedVertical' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'pane' => 'cbTabPaneNestedVertical' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null))) . '<div class="cb_tab_content cb_tab_vertical_nested" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
                 case "menu":
                     $oMenu[$pos] .= $this->startTab('CBMenu' . $pos, $tabTitle, $oTab->tabid, array('tab' => 'cbTabNavMenu' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'pane' => 'tab-pane cbTabPaneMenu' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'override' => true)) . '<div class="cb_tab_content cb_tab_menu" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
                 case "menunested":
                     $oMenuNest[$pos] .= $this->startTab('CBMenu' . $pos, $tabTitle, $oTab->tabid, array('tab' => 'cbTabNavMenuNested' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'pane' => 'tab-pane cbTabPaneMenuNested' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'override' => true)) . '<div class="cb_tab_content cb_tab_menu_nested" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
                 case "vertical":
                     $oVert[$pos] .= $this->startTab('CBVertical' . $pos, $tabTitle, $oTab->tabid, array('tab' => 'cbTabNavVertical' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null), 'pane' => 'cbTabPaneVertical' . ($oTab->cssclass ? ' ' . $oTab->cssclass : null))) . '<div class="cb_tab_content cb_tab_vertical" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
                 case "tab":
                 default:
                     $results[$pos] .= $this->startTab($pos, $tabTitle, $oTab->tabid, array('tab' => $oTab->cssclass, 'pane' => $oTab->cssclass)) . '<div class="cb_tab_content cb_tab_main" id="cb_tabid_' . $oTab->tabid . '">' . $tabContent . '</div>' . $this->endTab();
                     $i++;
                     break;
             }
         }
     }
     //foreach tab
     // Pass 4: concat different types, generating tabs preambles/postambles:
     foreach ($html as $pos => $val) {
         if ($oNest[$pos]) {
             $results[$pos] .= $this->startTab($pos, CBTxt::T('TABS_NESTED_MORE TABS_NESTED_HORIZONTAL_MORE', 'More'), $pos . 0, array('tab' => 'cbTabNavNested', 'pane' => 'cbTabPaneNested')) . '<div class="cb_tab_container cb_tab_nested_main" id="cb_position_' . $pos . '">' . $this->startPane('CBNested' . $pos, array('container' => 'cbTabsNested', 'nav' => 'cbTabsNavNested', 'content' => 'cbTabsContentNested')) . $oNest[$pos] . $this->endPane() . '</div>' . $this->endTab();
         }
         if ($oNestVert[$pos]) {
             $oVert[$pos] .= $this->startTab($pos, CBTxt::T('TABS_NESTED_MORE TABS_NESTED_VERTICAL_MORE', 'More'), $pos . 0, array('tab' => 'cbTabNavVertical', 'pane' => 'cbTabPaneVertical')) . '<div class="cb_tab_content cb_tab_nested_vertical" id="cb_position_' . $pos . '">' . $this->startPane('CBNestedVertical' . $pos, array('container' => 'cbTabsNestedVertical', 'nav' => 'cbTabsNavNestedVertical', 'content' => 'cbTabsContentNestedVertical')) . $oNestVert[$pos] . $this->endPane() . '</div>' . $this->endTab();
         }
         if ($oMenu[$pos] || $oMenuNest[$pos]) {
             static $oMenuJS = 0;
             if (!$oMenuJS++) {
                 $js = "\$( '.cbTabsMenuNavBar' ).on( 'click', '.navbar-toggle', function() {" . "if ( ! \$( this ).hasClass( 'dropdown-toggle' ) ) {" . "var navbar = \$( this ).closest( '.cbTabsMenuNavBar' ).find( '.navbar-collapse' );" . "var toggle = \$( this ).closest( '.cbTabsMenuNavBar' ).find( '.navbar-toggle' );" . "if ( toggle.hasClass( 'collapsed' ) ) {" . "navbar.addClass( 'in' );" . "toggle.removeClass( 'collapsed' );" . "} else {" . "navbar.removeClass( 'in' );" . "toggle.addClass( 'collapsed' );" . "}" . "}" . "}).find( '.cbScroller' ).cbscroller({" . "ignore: '.cbTabNavMenuMore,.cbTabNavMenuNested'," . "height: false" . "});" . "\$( '.cbTabsMenu' ).on( 'cbtabs.selected', function( e, event, cbtabs, tab ) {" . "var dropdownNav = \$( event.target ).closest( '.cbTabsMenuNavBar' );" . "if ( dropdownNav.length ) {" . "var toggle = dropdownNav.find( '.navbar-toggle' );" . "if ( ! toggle.hasClass( 'collapsed' ) ) {" . "toggle.click();" . "}" . "}" . "var dropdownTab = \$( event.target ).closest( '.cbTabNavMenuNested' );" . "if ( dropdownTab.length ) {" . "if ( dropdownTab.closest( '.cbTabNavMoreDropdown' ).length ) {" . "dropdownTab.siblings().removeClass( 'active' );" . "dropdownTab.addClass( 'active' );" . "}" . "}" . "});" . "\$( window ).load( function(){" . "\$( '.cbTabNavMenuMore' ).on( 'cbtooltip.show', function( e, cbtooltip, event, api ) {" . "if ( \$( this ).siblings( '.active' ).length ) {" . "api.elements.content.find( '.cbTabNav' ).removeClass( 'active' );" . "}" . "});" . "});";
                 $_CB_framework->outputCbJQuery($js, 'cbscroller');
             }
             if ($oMenuNest[$pos]) {
                 $more = '<li class="cbTabNavMore cbTabNavMenuMore cbTooltip dropdown" data-cbtooltip-tooltip-target="#cbtabs' . htmlspecialchars('CBMenu' . $pos) . 'More" data-cbtooltip-menu="true" data-cbtooltip-classes="qtip-nostyle cbTabNavMoreDropdown cbMenuDropdown" data-cbtooltip-adjust-y="0" data-cbtooltip-open-classes="open active">' . '<button type="button" class="cbTabNavMenuMoreBtn dropdown-toggle navbar-toggle">' . '<span class="icon-bar"></span>' . '<span class="icon-bar"></span>' . '<span class="icon-bar"></span>' . '</button>' . '<a href="javascript:void(0);" class="cbTabNavMenuMoreLink dropdown-toggle">' . CBTxt::T('TABS_NESTED_MORE TABS_NESTED_MENU_MORE', 'More') . ' <b class="fa fa-caret-down"></b></a>' . '<ul id="cbtabs' . htmlspecialchars('CBMenu' . $pos) . 'More" class="cbSubMenu dropdown-menu"></ul>' . '</li>';
                 $js = "\$( '#cbtabs" . addslashes('CBMenu' . $pos) . "' ).find( '.cbTabsNav:first' ).append( '" . addslashes($more) . "' );" . "\$( '#cbtabs" . addslashes('CBMenu' . $pos) . "' ).find( '.cbTabsNav:first' ).children( '.cbTabNavMenuNested' ).appendTo( '#cbtabs" . addslashes('CBMenu' . $pos) . "More' );";
                 $_CB_framework->outputCbJQuery($js);
             }
             $html[$pos] .= '<div class="cbTabs cbTabsMenu' . ($oMenuNest[$pos] ? ' cbTabsMenuMore' : null) . '" id="cbtabs' . htmlspecialchars('CBMenu' . $pos) . '">' . '<div class="cbTabsMenuNavBar' . ($oMenuNest[$pos] ? ' cbTabsMenuNavBarMore' : null) . ' navbar navbar-default">' . '<div class="container-fluid">' . '<div class="navbar-header">' . '<button type="button" class="cbTabsMenuNavBarToggle navbar-toggle collapsed">' . '<span class="icon-bar"></span>' . '<span class="icon-bar"></span>' . '<span class="icon-bar"></span>' . '</button>' . '</div>' . '<div class="collapse navbar-collapse cbScroller">' . '<div class="cbScrollerLeft hidden">' . '<button type="button" class="btn btn-xs btn-default"><span class="fa fa-angle-left"></span></button>' . '</div>' . '<ul class="cbTabsNav cbTabsMenuNav' . ($oMenuNest[$pos] ? ' cbTabsMenuNavMore' : null) . ' nav navbar-nav cbScrollerContent"></ul>' . '<div class="cbScrollerRight hidden">' . '<button type="button" class="btn btn-xs btn-default"><span class="fa fa-angle-right"></span></button>' . '</div>' . '</div>' . '</div>' . '</div>' . '<div class="cbTabsContent cbTabsMenuContent tab-content">' . $oMenu[$pos] . $oMenuNest[$pos] . '</div>' . '</div>';
         }
         if ($oVert[$pos]) {
             $html[$pos] .= $this->startPane('CBVertical' . $pos, array('container' => 'row cbTabsVertical', 'nav' => 'nav-stacked col-md-3 cbTabsNavVertical', 'content' => 'col-md-9 cbTabsContentVertical')) . $oVert[$pos] . $this->endPane();
         }
         if ($results[$pos]) {
             if ($val) {
                 $html[$pos] .= '<br />';
             }
             $html[$pos] .= $this->startPane($pos) . $results[$pos] . $this->endPane();
         }
     }
     // cache rendering if it's the complete rendering:
     if ($position == '') {
         $renderedCache[$user->id] = $html;
     }
     // check if pluginclass has been provided as the tab selected
     $tab = strtolower(stripslashes(cbGetParam($_REQUEST, 'tab', null)));
     if ($tab && isset($tabsMap[$tab])) {
         $_CB_framework->outputCbJQuery("\$( '#cbtabnav" . (int) $tabsMap[$tab] . " > a' ).click();");
     }
     return $html;
 }
Beispiel #25
0
 /**
  * Binds search range mode
  *
  * @param  FieldTable  $field
  * @param  UserTable   $searchVals
  * @param  array       $postdata
  * @param  string      $minName
  * @param  string      $maxName
  * @param  int         $list_compare_types  IF reason == 'search' : 0 : simple 'is' search, 1 : advanced search with modes, 2 : simple 'any' search
  * @return array|string|null
  */
 protected function _bindSearchRangeMode(&$field, &$searchVals, &$postdata, $minName, $maxName, $list_compare_types)
 {
     switch ($list_compare_types) {
         case 1:
             $value = $this->_bindSearchMode($field, $searchVals, $postdata, 'isisnot', $list_compare_types);
             break;
         case 2:
         case 0:
         default:
             if (cbGetParam($postdata, $minName) != null || cbGetParam($postdata, $maxName) != null) {
                 $value = 'is';
             } else {
                 $value = null;
             }
             break;
     }
     return $value;
 }
 /**
  * Installs plugin by upload from URL
  *
  * @return boolean
  */
 private function installPluginUpload()
 {
     global $_FILES;
     // Try extending time, as unziping/ftping took already quite some... :
     @set_time_limit(240);
     _CBsecureAboveForm('showPlugins');
     outputCbTemplate(2);
     outputCbJs(2);
     initToolTip(2);
     $installer = new cbInstallerPlugin();
     // Check if file uploads are enabled
     if (!(bool) ini_get('file_uploads')) {
         cbInstaller::showInstallMessage(CBTxt::T('The installer cannot continue before file uploads are enabled. Please use the install from directory method.'), CBTxt::T('Installer - Error'), false);
         return false;
     }
     // Check that the zlib is available
     if (!extension_loaded('zlib')) {
         cbInstaller::showInstallMessage(CBTxt::T('The installer cannot continue before zlib is installed'), CBTxt::T('Installer - Error'), false);
         return false;
     }
     $userfile = cbGetParam($_FILES, 'uploadfile', null);
     if (!$userfile || $userfile == null) {
         cbInstaller::showInstallMessage(CBTxt::T('No file selected'), CBTxt::T('Upload new plugin - error'), false);
         return false;
     }
     //	$userfile['tmp_name']	=	stripslashes( $userfile['tmp_name'] );
     //	$userfile['name']		=	stripslashes( $userfile['name'] );
     $msg = '';
     $localName = $_FILES['uploadfile']['name'];
     $resultdir = $this->uploadFile($_FILES['uploadfile']['tmp_name'], $localName, $msg);
     // $localName is updated here
     if ($resultdir === false) {
         cbInstaller::showInstallMessage($msg, CBTxt::T('UPLOAD_ERROR', 'Upload Error'), false);
         return false;
     }
     if (!$installer->upload($localName)) {
         if ($installer->unpackDir()) {
             $installer->cleanupInstall($localName, $installer->unpackDir());
         }
         cbInstaller::showInstallMessage($installer->getError(), CBTxt::T('UPLOAD_FAILED', 'Upload Failed'), false);
         return false;
     }
     $ret = $installer->install();
     $installer->cleanupInstall($localName, $installer->unpackDir());
     cbInstaller::showInstallMessage($installer->getError(), $ret ? CBTxt::T('UPLOAD_SUCCESS', 'Upload Success') : CBTxt::T('UPLOAD_FAILED', 'Upload Failed'), $ret);
     $installer->cleanupInstall($localName, $installer->unpackDir());
     return $ret;
 }
    function edituser($user, $option, $newCBuser, &$postdata)
    {
        global $_CB_framework, $_PLUGINS;
        $results = $_PLUGINS->trigger('onBeforeUserProfileEditDisplay', array(&$user, 2));
        if ($_PLUGINS->is_errors()) {
            echo "<script type=\"text/javascript\">alert(\"" . str_replace(array("\n", '<br />'), array('\\n', '\\n'), addslashes($_PLUGINS->getErrorMSG())) . "\"); window.history.go(-1); </script>\n";
            exit;
        }
        _CBsecureAboveForm('edituser');
        outputCbTemplate(2);
        initToolTip(2);
        $tabs = new cbTabs($_CB_framework->getUi() == 2 && !isset($_REQUEST['tab']) ? 1 : 0, 2);
        // use cookies in backend to remember selected tab.
        $tabcontent = $tabs->getEditTabs($user, $postdata);
        outputCbJs(2);
        global $_CB_Backend_Title;
        //OLD:	$_CB_Backend_Title	=	array( 0 => array( 'cbicon-48-users', "Community Builder User: <small>" . ( $user->id ? "Edit" . ' [ '. $user->username .' ]' : "New" ) . '</small>' ) );
        //NEW:
        $_CB_Backend_Title = array(0 => array('cbicon-48-users', CBTxt::T('Community Builder User') . ": <small>" . ($user->id ? CBTxt::T('Edit') . ' [ ' . $user->username . ' ]' : CBTxt::T('New')) . '</small>'));
        ob_start();
        if (defined('_CB_VALIDATE_NEW')) {
            cbimport('cb.validator');
            cbValidator::renderGenericJs();
            ?>

$('div.cbtoolbaractions .cbtoolbaraction').click( function() {
		if ( $(this).attr('href') ) {
			var taskVal = $(this).attr('href').substring(1);
		} else if ( $(this).attr('value') ) {
			taskVal = $(this).attr('value').substring(1);
		}
		$('#cbcheckedadminForm input[name=task]').val( taskVal );
		if (taskVal == 'showusers') {
			$('#cbcheckedadminForm')[0].submit();
		} else {
			$('#cbcheckedadminForm').submit();
		}
		return false;
	} );

<?php 
            $cbjavascript = ob_get_contents();
            ob_end_clean();
            $_CB_framework->outputCbJQuery($cbjavascript, array('metadata', 'validate'));
        } else {
            // old way:
            ?>
var cbDefaultFieldbackgroundColor;
function cbFrmSubmitButton() {
	var me = this.elements;
<?php 
            $version = checkJversion();
            if ($version == 1) {
                // var r = new RegExp("^[a-zA-Z](([\.\-a-zA-Z0-9@])?[a-zA-Z0-9]*)*$", "i");
                ?>
	var r = new RegExp("^[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]*$", "i");
<?php 
            } elseif ($version == -1) {
                ?>
	var r = new RegExp("[^A-Za-z0-9]", "i");
<?php 
            } else {
                ?>
	var r = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", "i");
<?php 
            }
            ?>
	var errorMSG = '';
	var iserror=0;
	if (cbDefaultFieldbackgroundColor === undefined) cbDefaultFieldbackgroundColor = ((me['username'].style.getPropertyValue) ? me['username'].style.getPropertyValue("backgroundColor") : me['username'].style.backgroundColor);
<?php 
            echo $tabs->fieldJS;
            ?>
	if (me['username'].value == "") {
		errorMSG += "<?php 
            echo str_replace(array("\n", "\r"), ' ', CBTxt::html_entity_decode(_REGWARN_UNAME));
            ?>
\n";
		me['username'].style.backgroundColor = "red";
		iserror=1;
	} else if (r.exec(me['username'].value) || (me['username'].value.length < 3)) {
		errorMSG += "<?php 
            echo str_replace(array("\n", "\r"), ' ', sprintf(CBTxt::html_entity_decode(_VALID_AZ09), CBTxt::html_entity_decode(_PROMPT_UNAME), 2));
            ?>
\n";
		me['username'].style.backgroundColor = "red";
		iserror=1;
	} else if (me['username'].style.backgroundColor.slice(0,3)=="red") {
		me['username'].style.backgroundColor = cbDefaultFieldbackgroundColor;
	}
	if ((me['password'].value != "") && (me['password'].value != me['password__verify'].value)){
		errorMSG += "<?php 
            echo CBTxt::html_entity_decode(_REGWARN_VPASS2);
            ?>
\n";
		me['password'].style.backgroundColor = "red"; me['password__verify'].style.backgroundColor = "red";
		iserror=1;
	} else {
		if (me['password'].style.backgroundColor.slice(0,3)=="red") me['password'].style.backgroundColor = cbDefaultFieldbackgroundColor;
		if (me['password__verify'].style.backgroundColor.slice(0,3)=="red") me['password__verify'].style.backgroundColor = cbDefaultFieldbackgroundColor;
	}
	if (!$('input[name^=\"gid\"],select[name^=\"gid\"]').val()) {
		errorMSG += '<?php 
            echo addslashes(CBTxt::T('You must assign user to a group.'));
            ?>
' + "\n";
		iserror=1;
	}

	// loop through all input elements in form
	var fieldErrorMessages = new Array;
	for (var i=0; i < me.length; i++) {
		// check if element is mandatory; here mosReq=1
		if ( (typeof(me[i].getAttribute('mosReq')) != "undefined") && ( me[i].getAttribute('mosReq') == 1) ) {
			if (me[i].type == 'radio' || me[i].type == 'checkbox') {
				var rOptions = me[me[i].getAttribute('name')];
				var rChecked = 0;
				if(rOptions.length > 1) {
					for (var r=0; r < rOptions.length; r++) {
						if ( (typeof(rOptions[r].getAttribute('mosReq')) != "undefined") && ( rOptions[r].getAttribute('mosReq') == 1) ) {
							if (rOptions[r].checked) {
								rChecked=1;
							}
						}
					}
				} else {
					if (me[i].checked) {
						rChecked=1;
					}
				}
				if(rChecked==0) {
					for (var k=0; k < me.length; k++) {
						if (me[i].getAttribute('name') == me[k].getAttribute('name')) {
							if (me[k].checked) {
								rChecked=1;
								break;
							}
						}
					}
				}
				if(rChecked==0) {
					var alreadyFlagged = false;
					for (var j = 0, n = fieldErrorMessages.length; j < n; j++) {
						if (fieldErrorMessages[j] == me[i].getAttribute('name')) {
							alreadyFlagged = true;
							break
						}
					}
					if ( ! alreadyFlagged ) {
						fieldErrorMessages.push(me[i].getAttribute('name'));
						// add up all error messages
						errorMSG += me[i].getAttribute('mosLabel') + ' : <?php 
            echo CBTxt::html_entity_decode(_UE_REQUIRED_ERROR);
            ?>
\n';
						// notify user by changing background color, in this case to red
						me[i].style.backgroundColor = "red";
						iserror=1;
					}
				} else if (me[i].style.backgroundColor.slice(0,3)=="red") me[i].style.backgroundColor = cbDefaultFieldbackgroundColor;
			}
			if (me[i].value == '') {
				// add up all error messages
				errorMSG += me[i].getAttribute('mosLabel') + ' : <?php 
            echo CBTxt::html_entity_decode(_UE_REQUIRED_ERROR);
            ?>
\n';
				// notify user by changing background color, in this case to red
				me[i].style.backgroundColor = "red";
				iserror=1;
			} else if (me[i].style.backgroundColor.slice(0,3)=="red") me[i].style.backgroundColor = cbDefaultFieldbackgroundColor;
		}
	}
	if(iserror==1) {
		alert(errorMSG);
		return false;
	} else {
		return true;
	}
}
$('#cbcheckedadminForm').submit( cbFrmSubmitButton );
$('div.cbtoolbaractions .cbtoolbaraction').click( function() {
		if ( $(this).attr('href') ) {
			var taskVal = $(this).attr('href').substring(1);
		} else if ( $(this).attr('value') ) {
			taskVal = $(this).attr('value').substring(1);
		}
		$('#cbcheckedadminForm input[name=task]').val( taskVal );
		if (taskVal == 'showusers') {
			$('#userEditTable input').val('');
			$('#cbcheckedadminForm')[0].submit();
		} else {
			$('#cbcheckedadminForm').submit();
		}
		return false;
	} );
<?php 
            $cbjavascript = ob_get_contents();
            ob_end_clean();
            $_CB_framework->outputCbJQuery($cbjavascript);
            // end of old way
        }
        if (is_array($results)) {
            echo implode('', $results);
        }
        $this->_overideWebFxLayout();
        ?>
<div id="cbErrorMessages"></div>
<form action="<?php 
        echo $_CB_framework->backendUrl('index.php');
        ?>
" method="post" name="adminForm" id="cbcheckedadminForm" enctype="multipart/form-data" autocomplete="off">
<?php 
        echo "<table cellspacing='0' cellpadding='4' border='0' width='100%' id='userEditTable'><tr><td width='100%'>\n";
        echo $tabcontent;
        echo "</td></tr></table>";
        ?>
  <input type="hidden" name="id" value="<?php 
        echo $user->id;
        ?>
" />
  <input type="hidden" name="newCBuser" value="<?php 
        echo $newCBuser;
        ?>
" />
  <input type="hidden" name="option" value="<?php 
        echo $option;
        ?>
" />
  <input type="hidden" name="task" value="save" />
  <?php 
        echo cbGetSpoofInputTag('user');
        ?>
</form>
<div style="align:center;">
<?php 
        echo getFieldIcons(2, true, true, "", "", true);
        if (isset($_REQUEST['tab'])) {
            $_CB_framework->outputCbJQuery("showCBTab( '" . addslashes(urldecode(stripslashes(cbGetParam($_REQUEST, 'tab')))) . "' );");
        }
        ?>
</div>
<?php 
    }
        /** @var CBController_plugin $cbController */
        $cbController->pluginMenu($option, $pluginId);
        break;
    default:
        _CBloadController('default');
        break;
}
ob_start();
/** @noinspection PhpIncludeInspection */
include $_CB_adminpath . '/comprofiler.toolbar.php';
$toolbars = trim(ob_get_contents());
ob_end_clean();
$_CB_framework->getAllJsPageCodes();
$html = ob_get_contents();
ob_end_clean();
if (in_array($taskPart1, array('fieldclass', 'tabclass', 'pluginclass')) || cbGetParam($_GET, 'no_html', 0) == 1 || cbGetParam($_GET, 'format') == 'raw') {
    echo $html;
} else {
    echo $_CB_framework->document->outputToHead();
    ?>
<div class="cbAdminMain cb_template cb_template_<?php 
    echo selectTemplate('dir');
    ?>
" style="margin:0; border-width: 0; padding: 0;width: 100% ;text-align: left;">
	<div class="cbAdminMainInner" id="cbAdminMainWrapper" style="margin: 0; border-width: 0; padding: 0; float: none; width: auto;">
<?php 
    if (checkJversion() >= 2 && !checkJversion('j3.0+')) {
        /** @noinspection PhpDeprecationInspection */
        JSubMenuHelper::addEntry(CBTxt::T('Control Panel'), 'index.php?option=com_comprofiler', $taskPart1 == '');
        if (Application::MyUser()->isAuthorizedToPerformActionOnAsset('core.manage', 'com_users')) {
            /** @noinspection PhpDeprecationInspection */
	function showUsers( $option, $task, $cid ) {
		global $_CB_database, $_CB_framework, $_POST, $_PLUGINS, $_CB_TxtIntStore;

		$this->_importNeeded();

		$limit						=	(int) $_CB_framework->getCfg( 'list_limit' );
		if ( $limit == 0 ) {
			$limit					=	10;
		}
		$filter_type				=	$_CB_framework->getUserStateFromRequest( "filter_type{$option}", 'filter_type', 0 );
		$filter_status				=	$_CB_framework->getUserStateFromRequest( "filter_status{$option}", 'filter_status', 0 );
		$filter_logged				=	intval( $_CB_framework->getUserStateFromRequest( "filter_logged{$option}", 'filter_logged', 0 ) );
		$lastCBlist					=	$_CB_framework->getUserState( "view{$option}lastCBlist", null );
		if( $lastCBlist == 'showusers' ) {
			if ( $task == 'showusers' ) {
				$limit				=	$_CB_framework->getUserStateFromRequest( "viewlistlimit", 'limit', $limit );
				$limitstart			=	$_CB_framework->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
			}
			$lastSearch 			=	$_CB_framework->getUserState( "search{$option}", null );
			$search					=	$_CB_framework->getUserStateFromRequest( "search{$option}", 'search', '' );
			if ( $lastSearch != $search ) {
				$limitstart			=	0;
				$_CB_framework->setUserState( "view{$option}limitstart", $limitstart );
			}
			$search					=	stripslashes( trim( ( $_CB_TxtIntStore->_iso != 'UTF-8' ) ? strtolower( $search ) : ( is_callable( 'mb_convert_case' ) ? mb_convert_case( $search, MB_CASE_LOWER, "UTF-8") : utf8_encode(strtolower(utf8_decode( $search ) ) ) ) ) );
		} else {
			$filter_type			=	0;
			$filter_status			=	0;
			$filter_logged			=	0;
			clearSearchBox();
			$search					=	'';
			$limitstart				=	0;
			$_CB_framework->setUserState( "view{$option}limitstart", $limitstart );
			$_CB_framework->setUserState( "view{$option}lastCBlist", "showusers" );
		}
	
		if ( $task !== 'showusers' ) {
			if ( $task == 'ajaxemailusers' ) {
				$limitstart			=	cbGetParam( $_POST, 'limitstart', 0 );
				$limit				=	cbGetParam( $_POST, 'limit', 0 );
			} else {
				$limitstart			=	0;
				if ( $task == 'emailusers' ) {
					$limit			=	101;		// so that first 100 users and more... is displayed.
				} else {
					$limit			=	cbGetParam( $_POST, 'limit', 0 );
				}
			}
		}
		
		$tablesSQL					=	array( 'u'	=> '#__users AS u' );
		$joinsSQL					=	array( 'ue'	=> 'LEFT JOIN #__comprofiler AS ue ON u.id = ue.id' );
		$tablesWhereSQL				=	array();
	
		if ( isset( $search ) && ( $search != "") ) {
			$tablesWhereSQL[]		=	"(u.username LIKE '%" . $_CB_database->getEscaped( $search, true ) . "%' OR u.email LIKE '%" . $_CB_database->getEscaped( $search, true ) . "%' OR u.name LIKE '%" . $_CB_database->getEscaped( $search, true ) . "%')";
		}
		if ( $filter_type ) {
			if ( checkJversion() == 2 ) {
				$tablesWhereSQL[]	=	"aro.group_id = " . (int)  $filter_type;
			} else {
				if ( $filter_type == 'Public Frontend' ) {
					$tablesWhereSQL[]	=	"(u.usertype = 'Registered' OR u.usertype = 'Author' OR u.usertype = 'Editor'OR u.usertype = 'Publisher')";
				} else if ( $filter_type == 'Public Backend' ) {
					$tablesWhereSQL[]	=	"( u.usertype = 'Manager' OR u.usertype = 'Administrator' OR u.usertype = 'Super Administrator' )";
				} else {
					$tablesWhereSQL[]	=	"u.usertype = " . $_CB_database->Quote( $filter_type );
				}
			}
		}
		$tBlocked					=	CBTxt::T('Blocked');
		$tEnabled					=	CBTxt::T('Enabled');
		$tUnconfirmed				=	CBTxt::T('Unconfirmed');
		$tConfirmed					=	CBTxt::T('Confirmed');
		$tUnapproved				=	CBTxt::T('Unapproved');
		$tDisapproved				=	CBTxt::T('Disapproved');
		$tApproved					=	CBTxt::T('Approved');
		$tBanned					=	CBTxt::T('Banned');
		$p							=	' + ';
		$userstates	=	array(
						$tBlocked											=>	'u.block = 1',
						$tEnabled											=>	'u.block = 0',
						$tUnconfirmed										=>	'ue.confirmed = 0',
						$tConfirmed											=>	'ue.confirmed = 1',
						$tUnapproved										=>	'ue.approved = 0',
						$tDisapproved										=>	'ue.approved = 2',
						$tApproved											=>	'ue.approved = 1',
						$tBanned											=>	'ue.banned <> 0',
						$tBlocked . $p . $tUnconfirmed . $p . $tUnapproved	=>	'(u.block = 1 AND ue.confirmed = 0 AND ue.approved = 0)',
						$tEnabled . $p . $tUnconfirmed . $p . $tUnapproved	=>	'(u.block = 0 AND ue.confirmed = 0 AND ue.approved = 0)',
						$tBlocked . $p . $tConfirmed   . $p . $tUnapproved	=>	'(u.block = 1 AND ue.confirmed = 1 AND ue.approved = 0)',
						$tEnabled . $p . $tConfirmed   . $p . $tUnapproved	=>	'(u.block = 0 AND ue.confirmed = 1 AND ue.approved = 0)',
						$tBlocked . $p . $tUnconfirmed . $p . $tDisapproved	=>	'(u.block = 1 AND ue.confirmed = 0 AND ue.approved = 2)',
						$tEnabled . $p . $tUnconfirmed . $p . $tDisapproved	=>	'(u.block = 0 AND ue.confirmed = 0 AND ue.approved = 2)',
						$tBlocked . $p . $tConfirmed   . $p . $tDisapproved	=>	'(u.block = 1 AND ue.confirmed = 1 AND ue.approved = 2)',
						$tEnabled . $p . $tConfirmed   . $p . $tDisapproved	=>	'(u.block = 0 AND ue.confirmed = 1 AND ue.approved = 2)',
						$tBlocked . $p . $tUnconfirmed . $p . $tApproved	=>	'(u.block = 1 AND ue.confirmed = 0 AND ue.approved = 1)',
						$tEnabled . $p . $tUnconfirmed . $p . $tApproved	=>	'(u.block = 0 AND ue.confirmed = 0 AND ue.approved = 1)',
						$tBlocked . $p . $tConfirmed   . $p . $tApproved	=>	'(u.block = 1 AND ue.confirmed = 1 AND ue.approved = 1)',
						$tEnabled . $p . $tConfirmed   . $p . $tApproved	=>	'(u.block = 0 AND ue.confirmed = 1 AND ue.approved = 1)',
						CBTxt::T('Avatar not approved')						=>	"(ue.avatar > '' AND ue.avatarapproved = 0)" );
		if ( $filter_status ) {
			$tablesWhereSQL[]		=	$userstates[$filter_status];
		}
		if ( $filter_logged == 1 ) {
			$tablesWhereSQL[]		=	"s.userid = u.id";
		} else if ($filter_logged == 2) {
			$tablesWhereSQL[]		=	"s.userid IS NULL";
		}
	
		// exclude any child group id's for this user
		//$_CB_framework->acl->_debug = true;
		$pgids						=	$_CB_framework->acl->get_group_children( userGID( $_CB_framework->myId() ), 'ARO', 'RECURSE' );
		if ( is_array( $pgids ) && (count( $pgids ) > 0 ) ) {
			if ( checkJversion() == 2 ) {
				$tablesWhereSQL[]	=	"( aro.group_id NOT IN ( " . implode( ',', $pgids ) . " ) )";
			} else {
				$tablesWhereSQL[]	=	"( u.gid NOT IN ( " . implode( ',', $pgids ) . " ) )";
			}
		}
		// Filter the checkmarked users only:
		if ( $task !== 'showusers' ) {
			if ( is_array( $cid ) && ( count( $cid ) > 0 ) ) {
				cbArrayToInts( $cid );
				$tablesWhereSQL[]		=	"( u.id IN ( " . implode( ',', $cid ) . " ) )";
			}
		}
	
		// Advanced searches:
		$myCbUser				=&	CBuser::getInstance( $_CB_framework->myId() );
		$myUser					=&	$myCbUser->getUserData();
		$tabs					=	$myCbUser->_getCbTabs();		//	new cbTabs( 0, 1 );		//TBD: later: this private method should not be called here, but the whole users-list should go into there and be called here.
		$allFields				=	$tabs->_getTabFieldsDb( null, $myUser, 'adminfulllist' );
		foreach ( $allFields as $k => $v ) {
			if ( in_array( $v->type, array( 'pm', 'status', 'formatname', 'hidden', 'delimiter', 'userparams' ) ) ) {
				unset( $allFields[$k] );		// delimiter, userparams do not have search for now!
			}
		}
		$searchVals				=	new stdClass();
		$list_compare_types		=	1;		// Advanced: all possibilities (WARNING: can be slow)
		$tableReferences		=	array( '#__comprofiler' => 'ue', '#__users' => 'u' );
		$searchesFromFields		=	$tabs->applySearchableContents( $allFields, $searchVals, $_POST, $list_compare_types );
		$whereFields			=	$searchesFromFields->reduceSqlFormula( $tableReferences, $joinsSQL, TRUE );
		if ( $whereFields ) {
			$tablesWhereSQL[]	=	'(' . $whereFields . ')';
		}
		$searchTabContent		=	$tabs->getSearchablesContents( $allFields, $myUser, $searchVals, $list_compare_types );
		
		if ($filter_logged == 1 || $filter_logged == 2) {
			$joinsSQL[]				.=	"\n INNER JOIN #__session AS s ON s.userid = u.id";
		// } else {		done later, to avoid blocking site:
		//	$joinsSQL[]				.=	"\n LEFT JOIN #__session AS s ON s.userid = u.id";
		}
	
		if ( checkJversion() == 2 ) {
			$joinsSQL[]				=	"INNER JOIN #__user_usergroup_map AS aro ON aro.user_id = u.id";			// map user to aro for selection (and display if no selection)
			if ( $filter_type ) {
				$joinsSQL[]			=	"LEFT JOIN #__user_usergroup_map AS arodisplay ON arodisplay.user_id = u.id";	// map user to aro for display of all groups
				$joinsSQL[]			=	"INNER JOIN #__usergroups AS g ON g.id = arodisplay.group_id"; 					// map aro to group for display group name
			} else {
				$joinsSQL[]			=	"INNER JOIN #__usergroups AS g ON g.id = aro.group_id"; 					// map aro to group
			}
		}
	
	   	$_PLUGINS->loadPluginGroup('user');
		$_PLUGINS->trigger( 'onBeforeBackendUsersListBuildQuery', array( &$tablesSQL, &$joinsSQL, &$tablesWhereSQL, $option ) );
	
		$queryFrom					=	"\n FROM " . implode( ', ', $tablesSQL )
									.	( count( $joinsSQL ) ? "\n " . implode( "\n ", $joinsSQL ) : '' )
									.	( count( $tablesWhereSQL ) ? "\n WHERE " . implode( ' AND ', $tablesWhereSQL ) : '' )
									;
	
		// Counting query:
		$query						=	"SELECT COUNT(DISTINCT u.id)"
									.	$queryFrom
									;
		$_CB_database->setQuery( $query );
		$total						=	$_CB_database->loadResult();
		if ( $total === null ) {
			echo $_CB_database->getErrorMsg();
		}
		if ( $total <= $limitstart ) {
			$limitstart				=	0;
		}
	
		cbimport( 'cb.pagination' );
		$pageNav					=	new cbPageNav( $total, $limitstart, $limit  );
	
		if ( checkJversion() == 2 ) {
			$grp_name				=	'title';
		} elseif ( checkJversion() == 1 ) {
			$grp_name				=	'name';
			$joinsSQL[]				=	"INNER JOIN #__core_acl_aro AS aro ON aro.value = u.id";					// map user to aro
			$joinsSQL[]				=	"INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.id";		// map aro to group
			$joinsSQL[]				=	"INNER JOIN #__core_acl_aro_groups AS g ON g.id = gm.group_id";
			$tablesWhereSQL[]		=	"aro.section_value = 'users'";
		} else {
			$grp_name				=	'name';
			$joinsSQL[]				=	"INNER JOIN #__core_acl_aro AS aro ON aro.value = u.id";					// map user to aro
			$joinsSQL[]				=	"INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.aro_id";	// map aro to group
			$joinsSQL[]				=	"INNER JOIN #__core_acl_aro_groups AS g ON g.group_id = gm.group_id";
			$tablesWhereSQL[]		=	"aro.section_value = 'users'";
		}
	
		$queryFrom					=	"\n FROM " . implode( ', ', $tablesSQL )
									.	( count( $joinsSQL ) ? "\n " . implode( "\n ", $joinsSQL ) : '' )
									.	( count( $tablesWhereSQL ) ? "\n WHERE " . implode( ' AND ', $tablesWhereSQL ) : '' )
									;
	
		// Main query:
		if ( checkJversion() == 2 ) {
			$query					=	"SELECT u.*, GROUP_CONCAT( DISTINCT g.$grp_name ORDER BY g.$grp_name SEPARATOR ', ') AS groupname, ue.approved, ue.confirmed"
									.	$queryFrom
									.	' GROUP BY u.id'
									;
		} else {
			$query					=	"SELECT DISTINCT u.*, g.$grp_name AS groupname, ue.approved, ue.confirmed"
									.	$queryFrom
									;
		}
		$_CB_database->setQuery( $query, (int) $pageNav->limitstart, (int) $pageNav->limit );
		$rows						=	$_CB_database->loadObjectList( null, 'moscomprofilerUser', array( &$_CB_database ) );
		if ($_CB_database->getErrorNum()) {
			echo $_CB_database->stderr();
			return false;
		}
		// creates the CBUsers in cache corresponding to the $users:
		foreach ( array_keys( $rows ) as $k) {
			// do not do this otherwise substitutions do not work: 
			// CBuser::setUserGetCBUserInstance( $rows[$k] );
		}
	
		$template				=	'SELECT COUNT(s.userid) FROM #__session AS s WHERE s.userid = ';
		$n						=	count( $rows );
		for ( $i = 0; $i < $n; $i++ ) {
			$row				=	&$rows[$i];
			$query				=	$template . (int) $row->id;
			$_CB_database->setQuery( $query );
			$row->loggedin		=	$_CB_database->loadResult();
		}
	
		$select_tag_attribs		=	'class="inputbox" size="1" onchange="document.adminForm.submit( );"';
		$inputTextExtras		=	'';
		if ( $task != 'showusers' ) {
			$inputTextExtras	=	' disabled="disabled"';
			$select_tag_attribs	.=	$inputTextExtras;
		}
	
		// get list of Log Status for dropdown filter
		$logged[]				=	moscomprofilerHTML::makeOption( 0, CBTxt::T('- Select Login State -'));
		$logged[]				=	moscomprofilerHTML::makeOption( 1, CBTxt::T('Logged In'));
		$lists['logged']		=	moscomprofilerHTML::selectList( $logged, 'filter_logged', $select_tag_attribs, 'value', 'text', "$filter_logged", 2 );
	
		// get list of Groups for dropdown filter
		if ( checkJversion() == 2 ) {
			$query				=	"SELECT id AS value, title AS text"
								.	"\n FROM #__usergroups";
		} else {
			$query				=	"SELECT name AS value, name AS text"
								.	"\n FROM #__core_acl_aro_groups"
								.	"\n WHERE name != 'ROOT'"
								.	"\n AND name != 'USERS'";
		}
	
		$types[]				=	moscomprofilerHTML::makeOption( '0', CBTxt::T('- Select Group -') );
		$_CB_database->setQuery( $query );
		$types					=	array_merge( $types, $_CB_database->loadObjectList() );
		$lists['type']			=	moscomprofilerHTML::selectList( $types, 'filter_type', $select_tag_attribs, 'value', 'text', "$filter_type", 2 );
	
		$status[]				=	moscomprofilerHTML::makeOption( 0, CBTxt::T('- Select User Status -'));
		foreach ( array_keys( $userstates ) as $k ) {
			$status[]			=	moscomprofilerHTML::makeOption( $k, $k );
		}
		$lists['status']		=	moscomprofilerHTML::selectList( $status, 'filter_status', $select_tag_attribs, 'value', 'text', "$filter_status", 2 );
	
		$pluginAdditions		=	$_PLUGINS->trigger( 'onAfterBackendUsersList', array( 1, &$rows, &$pageNav, &$search, &$lists, $option, $select_tag_attribs ) );
		$pluginColumns			=	array();
		foreach ( $pluginAdditions as $addition ) {
			if ( is_array( $addition ) ) {
				$pluginColumns	=	array_merge( $pluginColumns, $addition );
			}
		}
	
		if ( $task == 'showusers' ) {
			$usersView			=	_CBloadView( 'users' );
			$usersView->showUsers( $rows, $pageNav, $search, $option, $lists, $pluginColumns, $inputTextExtras, $searchTabContent );
		} else {
			$emailSubject		=	stripslashes( cbGetParam( $_POST, 'emailsubject', '' ) );
			$emailBody			=	stripslashes( cbGetParam( $_POST, 'emailbody', '', _CB_ALLOWRAW | _CB_NOTRIM ) );
			$emailsPerBatch		=	stripslashes( cbGetParam( $_POST, 'emailsperbatch', 50 ) );
			$emailPause			=	stripslashes( cbGetParam( $_POST, 'emailpause', 30 ) );
			$simulationMode		=	stripslashes( cbGetParam( $_POST, 'simulationmode', '' ) );
			if ( count( $cid ) > 0 && count( $cid ) < $total ) {
				$total			=	count( $cid );
			}
			if ( $task == 'emailusers' ) {
				$pluginRows		=	$_PLUGINS->trigger( 'onBeforeBackendUsersEmailForm', array( &$rows, &$pageNav, &$search, &$lists, &$cid, &$emailSubject, &$emailBody, &$inputTextExtras, &$select_tag_attribs, $simulationMode, $option ) );
				$usersView		=	_CBloadView( 'users' );
				$usersView->emailUsers( $rows, $total, $search, $option, $lists, $cid, $inputTextExtras, $searchTabContent, $emailSubject, $emailBody, $emailsPerBatch, $emailPause, $simulationMode, $pluginRows );
			} elseif ( $task == 'startemailusers' ) {
				$pluginRows		=	$_PLUGINS->trigger( 'onBeforeBackendUsersEmailStart', array( &$rows, $total, $search, $lists, $cid, &$emailSubject, &$emailBody, &$inputTextExtras, $simulationMode, $option ) );
				$usersView		=	_CBloadView( 'users' );
				$usersView->startEmailUsers( $rows, $search, $option, $lists, $cid, $inputTextExtras, $searchTabContent, $emailSubject, $emailBody, $emailsPerBatch, $emailPause, $total, $simulationMode, $pluginRows );
			} elseif ( $task == 'ajaxemailusers' ) {
				$this->_cbadmin_emailUsers( $rows, $emailSubject, $emailBody, $limitstart, $limit, $total, $simulationMode );
			}
		}
		return true;
	}
Beispiel #30
-1
 /**
  * Draws Users list (ECHO)
  *
  * @param  int      $userId
  * @param  int      $listId
  * @param  array    $postData
  * @return void
  */
 public function drawUsersList($userId, $listId, $postData)
 {
     global $_CB_database, $_PLUGINS;
     $_PLUGINS->loadPluginGroup('user');
     $searchData = cbGetParam($postData, 'search');
     $limitstart = (int) cbGetParam($postData, 'limitstart');
     $searchMode = (int) cbGetParam($postData, 'searchmode', 0);
     $random = (int) cbGetParam($postData, 'rand', 0);
     $cbUser = CBuser::getInstance((int) $userId, false);
     $user = $cbUser->getUserData();
     $search = null;
     $input = array();
     $publishedLists = array();
     $query = 'SELECT *' . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_lists') . "\n WHERE " . $_CB_database->NameQuote('published') . " = 1" . "\n AND " . $_CB_database->NameQuote('viewaccesslevel') . " IN " . $_CB_database->safeArrayOfIntegers(Application::MyUser()->getAuthorisedViewLevels()) . "\n ORDER BY " . $_CB_database->NameQuote('ordering');
     $_CB_database->setQuery($query);
     /** @var ListTable[] $userLists */
     $userLists = $_CB_database->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($_CB_database));
     if ($userLists) {
         foreach ($userLists as $userList) {
             $publishedLists[] = moscomprofilerHTML::makeOption((int) $userList->listid, strip_tags($cbUser->replaceUserVars($userList->title, false, false)));
             if (!$listId && $userList->default) {
                 $listId = (int) $userList->listid;
             }
         }
         if (!$listId) {
             $listId = (int) $userLists[0]->listid;
         }
     }
     if (!$listId) {
         echo CBTxt::Th('UE_NOLISTFOUND', 'There are no published user lists!');
         return;
     }
     if ($userLists) {
         $input['plists'] = moscomprofilerHTML::selectList($publishedLists, 'listid', 'class="form-control input-block" onchange="this.form.submit();"', 'value', 'text', (int) $listId, 1);
     }
     $row = self::getInstance((int) $listId);
     if (!$row) {
         echo CBTxt::Th('UE_LIST_DOES_NOT_EXIST', 'This list does not exist');
         return;
     }
     if (!$cbUser->authoriseView('userslist', $row->listid)) {
         echo CBTxt::Th('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!');
         return;
     }
     $params = new Registry($row->params);
     if ($params->get('hotlink_protection', 0) == 1) {
         if ($searchData !== null || $limitstart) {
             cbSpoofCheck('userslist', 'GET');
         }
     }
     $limit = (int) $params->get('list_limit', 30);
     if (!$limit) {
         $limit = 30;
     }
     if ($params->get('list_paging', 1) != 1) {
         $limitstart = 0;
     }
     $isModerator = Application::MyUser()->isGlobalModerator();
     $_PLUGINS->trigger('onStartUsersList', array(&$listId, &$row, &$search, &$limitstart, &$limit));
     // Prepare query variables:
     $userGroupIds = explode('|*|', $row->usergroupids);
     $orderBy = self::getSorting($listId, $userId, $random);
     $filterBy = self::getFiltering($listId, $userId);
     $columns = self::getColumns($listId, $userId);
     // Grab all the fields the $user can access:
     $tabs = new cbTabs(0, 1);
     $fields = $tabs->_getTabFieldsDb(null, $user, 'list');
     // Build the field SQL:
     $tableReferences = array('#__comprofiler' => 'ue', '#__users' => 'u');
     $searchableFields = array();
     $fieldsSQL = cbUsersList::getFieldsSQL($columns, $fields, $tableReferences, $searchableFields, $params);
     $_PLUGINS->trigger('onAfterUsersListFieldsSql', array(&$columns, &$fields, &$tableReferences));
     // Build the internal joins and where statements best off list parameters:
     $tablesSQL = array();
     $joinsSQL = array();
     $tablesWhereSQL = array();
     if ($isModerator) {
         if (!$params->get('list_show_blocked', 0)) {
             $tablesWhereSQL['block'] = 'u.block = 0';
         }
         if (!$params->get('list_show_banned', 1)) {
             $tablesWhereSQL['banned'] = 'ue.banned = 0';
         }
         if (!$params->get('list_show_unapproved', 0)) {
             $tablesWhereSQL['approved'] = 'ue.approved = 1';
         }
         if (!$params->get('list_show_unconfirmed', 0)) {
             $tablesWhereSQL['confirmed'] = 'ue.confirmed = 1';
         }
     } else {
         $tablesWhereSQL = array('block' => 'u.block = 0', 'approved' => 'ue.approved = 1', 'confirmed' => 'ue.confirmed = 1', 'banned' => 'ue.banned = 0');
     }
     $joinsSQL[] = 'JOIN #__user_usergroup_map g ON g.`user_id` = u.`id`';
     if ($userGroupIds) {
         $tablesWhereSQL['gid'] = 'g.group_id IN ' . $_CB_database->safeArrayOfIntegers($userGroupIds);
     }
     foreach ($tableReferences as $table => $name) {
         if ($name == 'u') {
             $tablesSQL[] = $table . ' ' . $name;
         } else {
             $joinsSQL[] = 'JOIN ' . $table . ' ' . $name . ' ON ' . $name . '.`id` = u.`id`';
         }
     }
     // Build the search criteria:
     $searchValues = new stdClass();
     $searchesFromFields = $tabs->applySearchableContents($searchableFields, $searchValues, $postData, $params->get('list_compare_types', 0));
     $whereFields = $searchesFromFields->reduceSqlFormula($tableReferences, $joinsSQL, true);
     if ($whereFields) {
         $tablesWhereSQL[] = '(' . $whereFields . ')';
     }
     $_PLUGINS->trigger('onBeforeUsersListBuildQuery', array(&$tablesSQL, &$joinsSQL, &$tablesWhereSQL));
     // Construct the FROM and WHERE for the userlist query:
     $queryFrom = "FROM " . implode(', ', $tablesSQL) . (count($joinsSQL) ? "\n " . implode("\n ", $joinsSQL) : '') . "\n WHERE " . implode("\n AND ", $tablesWhereSQL) . " " . $filterBy;
     $_PLUGINS->trigger('onBeforeUsersListQuery', array(&$queryFrom, 1, $listId));
     // $ui = 1 (frontend)
     $errorMsg = null;
     // Checks if the list is being actively searched and it allows searching; otherwise reset back to normal:
     $searchCount = count(get_object_vars($searchValues));
     if ($params->get('list_search', 1) > 0 && $params->get('list_search_empty', 0) && !$searchCount) {
         $searchMode = 1;
         $listAll = false;
     } else {
         $listAll = $searchCount ? true : false;
     }
     if ($searchMode == 0 || $searchMode == 1 && $searchCount || $searchMode == 2) {
         // Prepare the userlist count query for pagination:
         $_CB_database->setQuery("SELECT COUNT( DISTINCT u.id ) " . $queryFrom);
         $total = $_CB_database->loadResult();
         if ($limit > $total || $limitstart >= $total) {
             $limitstart = 0;
         }
         // Prepare the actual userlist query to build a list of users:
         $query = "SELECT DISTINCT ue.*, u.*, '' AS 'NA' " . ($fieldsSQL ? ", " . $fieldsSQL . " " : '') . $queryFrom . " " . $orderBy;
         $_CB_database->setQuery($query, (int) $limitstart, (int) $limit);
         /** @var UserTable[] $users */
         $users = $_CB_database->loadObjectList(null, '\\CB\\Database\\Table\\UserTable', array($_CB_database));
         if (!$_CB_database->getErrorNum()) {
             $profileLink = $params->get('allow_profilelink', 1);
             // If users exist lets cache them and disable profile linking if necessary:
             if ($users) {
                 foreach (array_keys($users) as $k) {
                     // Add this user to cache:
                     CBuser::setUserGetCBUserInstance($users[$k]);
                     if (!$profileLink) {
                         $users[$k]->set('_allowProfileLink', 0);
                     }
                 }
             }
         } else {
             $errorMsg = CBTxt::T('UE_ERROR_IN_QUERY_TURN_SITE_DEBUG_ON_TO_VIEW', 'There is an error in the database query. Site admin can turn site debug to on to view and fix the query.');
         }
         if ($searchCount) {
             $search = '';
         } else {
             $search = null;
         }
         if ($search === null && ($searchMode == 1 && $searchCount || $searchMode == 2)) {
             $search = '';
         }
     } else {
         $total = 0;
         $users = array();
         if ($search === null) {
             $search = '';
         }
     }
     $pageNav = new cbPageNav($total, $limitstart, $limit);
     HTML_comprofiler::usersList($row, $users, $columns, $fields, $input, $search, $searchMode, $pageNav, $user, $searchableFields, $searchValues, $tabs, $errorMsg, $listAll, $random);
 }