/**
  * Custom install method
  * @param boolean True if installing from directory
  */
 function install($p_fromdir = null)
 {
     global $_CB_framework, $_CB_database, $ueConfig, $_PLUGINS;
     if (!$this->preInstallCheck($p_fromdir, $this->elementType)) {
         return false;
     }
     $cbInstallXML =& $this->i_xmldocument;
     // Get name
     $e =& $cbInstallXML->getElementByPath('name');
     $this->elementName($e->data());
     $cleanedElementName = strtolower(str_replace(array(" ", "."), array("", "_"), $this->elementName()));
     // Get plugin filename
     $files_element =& $cbInstallXML->getElementByPath('files');
     foreach ($files_element->children() as $file) {
         if ($file->attributes("plugin")) {
             $this->elementSpecial($file->attributes("plugin"));
         }
     }
     $fileNopathNoext = null;
     $matches = array();
     if (preg_match("/^.*[\\/\\\\](.*)\\..*\$/", $this->installFilename(), $matches)) {
         $fileNopathNoext = $matches[1];
     }
     if (!($fileNopathNoext && $this->elementSpecial() == $fileNopathNoext)) {
         $this->setError(1, 'Installation filename `' . $fileNopathNoext . '` (with .xml) does not match main php file plugin attribute `' . $this->elementSpecial() . '` in the plugin xml file<br />');
         return false;
     }
     $cleanedMainFileName = strtolower(str_replace(array(" ", "."), array("", "_"), $this->elementSpecial()));
     // check version
     $v =& $cbInstallXML->getElementByPath('version');
     $version = $v->data();
     if ($version == $ueConfig['version'] || ($version == "1.9" || $version == "1.9 RC" || $version == "1.8.1" || $version == "1.8" || $version == "1.8 RC3" || $version == "1.8 RC2" || $version == "1.8 RC" || $version == "1.7.1" || $version == "1.7" || $version == "1.7 RC" || $version == "1.4" || $version == "1.4 RC" || $version == "1.3.1" || $version == "1.3" || $version == "1.2.3" || $version == "1.2.2" || $version == "1.2.1" || $version == "1.2" || $version == "1.2 RC 4" || $version == "1.2 RC 3" || $version == "1.2 RC 2" || $version == "1.2 RC" || $version == "1.0 RC 2" || $version == "1.0" || $version == "1.0.1" || $version == "1.0.2" || $version == "1.1")) {
     } else {
         $this->setError(1, 'Plugin version (' . $version . ') different from Community Builder version (' . $ueConfig['version'] . ')');
         return false;
     }
     $backendMenu = "";
     $adminmenusnode =& $cbInstallXML->getElementByPath('adminmenus');
     if ($adminmenusnode) {
         $menusArr = array();
         //cycle through each menu
         foreach ($adminmenusnode->children() as $menu) {
             if ($menu->name() == "menu") {
                 $action = $menu->attributes('action');
                 $text = getLangDefinition($menu->data());
                 $menusArr[] = $text . ":" . $action;
             }
         }
         $backendMenu = implode(",", $menusArr);
     }
     $folder = strtolower($cbInstallXML->attributes('group'));
     if (cbStartOfStringMatch($folder, '/')) {
         $this->elementDir($_CB_framework->getCfg('absolute_path') . $folder . '/');
         $subFolder = $folder;
     } else {
         $subFolder = ($folder == 'user' ? 'plug_' : '') . $cleanedElementName;
         $this->elementDir($_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' . $folder . '/' . $subFolder . '/');
     }
     $upgradeMethod = $this->installMethod($cbInstallXML->attributes('method'));
     if (file_exists($this->elementDir()) && !$upgradeMethod) {
         $this->setError(1, 'Another plugin is already using directory: "' . $this->elementDir() . '"');
         return false;
     }
     $parentFolder = preg_replace('/\\/[^\\/]*\\/?$/', '/', $this->elementDir());
     if (!file_exists($parentFolder)) {
         $this->setError(1, sprintf('The directory in which the plugin should install does not exist: probably the parent extension is not installed. Install parent extension first. Plugin parent directory missing: "%s" and plugin directory specified by installer for installation "%s"', $parentFolder, $this->elementDir()));
         return false;
     }
     if (!file_exists($this->elementDir()) && !$this->mosMakePath($this->elementDir())) {
         $this->setError(1, 'Failed to create directory' . ' "' . $this->elementDir() . '"');
         return false;
     }
     // Copy files from package:
     if ($this->parseFiles('files', 'plugin', 'No file is marked as plugin file') === false) {
         $this->cleanupInstall(null, $this->elementDir());
         // try removing directory and content just created successfully
         return false;
     }
     // Copy XML file from package (needed for creating fields of new types and so on):
     if ($this->copySetupFile('front') === false) {
         $this->cleanupInstall(null, $this->elementDir());
         // try removing directory and content just created successfully
         return false;
     }
     // Check to see if plugin already exists in db
     $_CB_database->setQuery("SELECT id FROM #__comprofiler_plugin WHERE element = '" . $this->elementSpecial() . "' AND folder = '" . $subFolder . "'");
     if (!$_CB_database->query()) {
         $this->setError(1, 'SQL error' . ': ' . $_CB_database->stderr(true));
         $this->cleanupInstall(null, $this->elementDir());
         // try removing directory and content just created successfully
         return false;
     }
     $pluginid = $_CB_database->loadResult();
     $pluginRowWasNotExisting = !$pluginid;
     $row = new moscomprofilerPlugin($_CB_database);
     $row->id = $pluginid;
     if (!$pluginid) {
         $row->name = $this->elementName();
         $row->ordering = 99;
     }
     $row->type = $folder;
     if ($row->type == 'language') {
         $row->published = 1;
     }
     $row->folder = $subFolder;
     $row->backend_menu = $backendMenu;
     $row->iscore = 0;
     $row->access = 0;
     $row->client_id = 0;
     $row->element = $this->elementSpecial();
     if (!$row->store()) {
         $this->setError(1, 'SQL error' . ': ' . $row->getError());
         $this->cleanupInstall(null, $this->elementDir());
         // try removing directory and content just created successfully
         return false;
     }
     if (!$pluginid) {
         $pluginid = $_CB_database->insertid();
     }
     $_PLUGINS->_setLoading($row, true);
     // Are there any Database statements ??
     $db =& $cbInstallXML->getElementByPath('database');
     if ($db !== false && count($db->children()) > 0) {
         cbimport('cb.sql.upgrader');
         $sqlUpgrader = new CBSQLupgrader($_CB_database, false);
         //$sqlUpgrader->setDryRun( true );
         $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedElementName, true, null);
         /*
         var_dump( $success );
         echo "<br>\nERRORS: " . $sqlUpgrader->getErrors( "<br /><br />\n\n", "<br />\n" );
         echo "<br>\nLOGS: " . $sqlUpgrader->getLogs( "<br /><br />\n\n", "<br />\n" );
         exit;
         */
         if (!$success) {
             $this->setError(1, "Plugin database XML SQL Error " . $sqlUpgrader->getErrors());
             if ($pluginRowWasNotExisting) {
                 $this->deleteTabAndFieldsOfPlugin($row->id);
                 // delete tabs and private fields of plugin
                 $row->delete();
             }
             $this->cleanupInstall(null, $this->elementDir());
             // try removing directory and content just created successfully
             return false;
         }
     }
     $e =& $cbInstallXML->getElementByPath('description');
     if ($e !== false) {
         $desc = $this->elementName() . '<div>' . $e->data() . '</div>';
         $this->setError(0, $desc);
     }
     //If type equals user then check for tabs and fields
     if ($folder == 'user') {
         $tabsnode =& $cbInstallXML->getElementByPath('tabs');
         if ($tabsnode) {
             //cycle through each tab
             foreach ($tabsnode->children() as $tab) {
                 if ($tab->name() == 'tab') {
                     //install each tab
                     $tabid = $this->installTab($pluginid, $tab);
                     if ($tabid) {
                         //get all fields in the tab
                         $fieldsnode = $tab->getElementByPath('fields');
                         if ($fieldsnode) {
                             //cycle through each field
                             foreach ($fieldsnode->children() as $field) {
                                 if ($field->name() == "field") {
                                     //install each field
                                     //echo "installing field...";
                                     $fieldid = $this->installField($pluginid, $tabid, $field);
                                     //get all fieldvalues for the field
                                     //cycle through each fieldValue
                                     foreach ($field->children() as $fieldValue) {
                                         if ($fieldValue->name() == "fieldvalue") {
                                             $this->installFieldValue($fieldid, $fieldValue);
                                         }
                                     }
                                 }
                             }
                         }
                     } else {
                         if ($pluginRowWasNotExisting) {
                             if ($db) {
                                 $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedElementName, 'drop', null);
                             }
                             $this->deleteTabAndFieldsOfPlugin($row->id);
                             // delete tabs and private fields of plugin
                             $row->delete();
                         }
                         $this->cleanupInstall(null, $this->elementDir());
                         // try removing directory and content just created successfully
                         return false;
                     }
                 }
             }
         }
         // (re)install field types of plugin:
         $fieldtypes =& $cbInstallXML->getElementByPath('fieldtypes');
         if ($fieldtypes) {
             foreach ($fieldtypes->children() as $typ) {
                 if ($typ->name() == 'field') {
                     $this->installFieldType($pluginid, $typ->attributes('type'));
                 }
             }
         }
     }
     // Are there any SQL queries??
     $query_element =& $cbInstallXML->getElementByPath('install/queries');
     if ($query_element) {
         foreach ($query_element->children() as $query) {
             $_CB_database->setQuery(trim($query->data()));
             if (!$_CB_database->query()) {
                 $this->setError(1, "SQL Error " . $_CB_database->stderr(true));
                 if ($pluginRowWasNotExisting) {
                     if ($db) {
                         $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedElementName, 'drop', null);
                     }
                     $this->deleteTabAndFieldsOfPlugin($row->id);
                     // delete tabs and private fields of plugin
                     $row->delete();
                 }
                 $this->cleanupInstall(null, $this->elementDir());
                 // try removing directory and content just created successfully
                 return false;
             }
         }
     }
     // Is there an installfile
     $installfile_elemet =& $cbInstallXML->getElementByPath('installfile');
     if ($installfile_elemet) {
         // check if parse files has already copied the install.component.php file (error in 3rd party xml's!)
         if (!file_exists($this->elementDir() . $installfile_elemet->data())) {
             if (!$this->copyFiles($this->installDir(), $this->elementDir(), array($installfile_elemet->data()), $this->installMethod())) {
                 $this->setError(1, 'Could not copy PHP install file.');
                 if ($pluginRowWasNotExisting) {
                     if ($db) {
                         $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedElementName, 'drop', null);
                     }
                     $this->deleteTabAndFieldsOfPlugin($row->id);
                     // delete tabs and private fields of plugin
                     $row->delete();
                 }
                 $this->cleanupInstall(null, $this->elementDir());
                 // try removing directory and content just created successfully
                 return false;
             }
         }
         $this->hasInstallfile(true);
         $this->installFile($installfile_elemet->data());
     }
     // Is there an uninstallfile
     $uninstallfile_elemet =& $cbInstallXML->getElementByPath('uninstallfile');
     if ($uninstallfile_elemet) {
         if (!file_exists($this->elementDir() . $uninstallfile_elemet->data())) {
             if (!$this->copyFiles($this->installDir(), $this->elementDir(), array($uninstallfile_elemet->data(), $this->installMethod()))) {
                 $this->setError(1, 'Could not copy PHP uninstall file');
                 if ($pluginRowWasNotExisting) {
                     if ($db) {
                         $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedElementName, 'drop', null);
                     }
                     $this->deleteTabAndFieldsOfPlugin($row->id);
                     // delete tabs and private fields of plugin
                     $row->delete();
                 }
                 $this->cleanupInstall(null, $this->elementDir());
                 // try removing directory and content just created successfully
                 return false;
             }
         }
     }
     if ($this->hasInstallfile()) {
         if (is_file($this->elementDir() . $this->installFile())) {
             require_once $this->elementDir() . $this->installFile();
             $ret = call_user_func_array('plug_' . $cleanedMainFileName . '_install', array());
             if ($ret != '') {
                 $this->setError(0, $desc . $ret);
             }
         }
     }
     if ($db !== false && count($db->children()) > 0) {
         HTML_comprofiler::fixcbdbShowResults($sqlUpgrader, true, false, $success, array(), array(), $this->elementName(), 1, false);
     }
     return true;
 }
/**
* changes the access level of a record
* @param integer The increment to reorder by
*/
function accessMenu($uid, $access, $option)
{
    global $_CB_framework, $_CB_database;
    switch ($access) {
        case 'accesspublic':
            $access = 0;
            break;
        case 'accessregistered':
            $access = 1;
            break;
        case 'accessspecial':
            $access = 2;
            break;
    }
    $row = new moscomprofilerPlugin($_CB_database);
    $row->load((int) $uid);
    $row->access = $access;
    if (!$row->check()) {
        return $row->getError();
    }
    if (!$row->store()) {
        return $row->getError();
    }
    cbRedirect($_CB_framework->backendUrl("index.php?option={$option}&task=showPlugins"));
    return null;
}
 /**
  * Saves the CB plugin params after an edit form submit
  */
 function savePluginParams($option, $task)
 {
     global $_CB_framework, $_CB_database, $_POST;
     if (isset($_POST['params'])) {
         $_POST['params'] = cbParamsEditorController::getRawParamsMagicgpcEscaped($_POST['params']);
     } else {
         $_POST['params'] = null;
     }
     $oldrow = new moscomprofilerPlugin($_CB_database);
     if (isset($_POST['id'])) {
         $oldrow->load((int) $_POST['id']);
         // Check if user is a super user:
         if (!$_CB_framework->acl->amIaSuperAdmin()) {
             // Check if user belongs to access:
             if (!in_array($oldrow->access, CBuser::getMyInstance()->getAuthorisedViewLevelsIds(true))) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
         }
     }
     $row = new moscomprofilerPlugin($_CB_database);
     if (!$row->bind($_POST)) {
         echo "<script type=\"text/javascript\"> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
         exit;
     }
     // Set defaults if nothing is found
     // Also check if oldrow exists to use its current value or default
     // This prevents a plugin from storing to database with null values when some inputs are set disabled:
     $defaultaccess = checkJversion() >= 2 ? 1 : 0;
     if ($row->access == '') {
         $row->access = $oldrow->access != '' ? $oldrow->access : $defaultaccess;
     }
     if ($row->ordering == '') {
         $row->ordering = $oldrow->ordering != '' ? $oldrow->ordering : 999;
     }
     if ($row->published == '') {
         $row->published = $oldrow->published != '' ? $oldrow->published : 1;
     }
     if (!$row->check()) {
         echo "<script type=\"text/javascript\"> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
         exit;
     }
     // Check if user is a super user:
     if (!$_CB_framework->acl->amIaSuperAdmin()) {
         $canEditState = CBuser::getMyInstance()->authoriseAction('core.edit.state');
         // Check if user belongs to access
         // Check if row exists and if access is different from existing row
         // Check if row doesn't exist and if access is different from default
         // Check if user can edit status:
         if ($row->access != '' && !in_array($row->access, CBuser::getMyInstance()->getAuthorisedViewLevelsIds(true))) {
             echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
             exit;
         }
         // Check if user can edit status:
         if (!$canEditState) {
             // Check if row exists and if access is different from existing row
             // Check if row doesn't exist and if access is different from default
             if ($oldrow->id && ($row->access != '' && $oldrow->access != $row->access) || !$oldrow->id && ($row->access != '' && $row->access != $defaultaccess)) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
             // Check if row exists and if ordering is different from existing row
             // Check if row doesn't exist and if ordering is different from default
             if ($oldrow->id && ($row->ordering != '' && $oldrow->ordering != $row->ordering) || !$oldrow->id && ($row->ordering != '' && $row->ordering != 999)) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
             // Check if row exists and if published is different from existing row
             // Check if row doesn't exist and if published is different from default
             if ($oldrow->id && ($row->published != '' && $oldrow->published != $row->published) || !$oldrow->id && ($row->published != '' && $row->published != 1)) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
         }
     }
     if (!$row->store()) {
         echo "<script type=\"text/javascript\"> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
         exit;
     }
     $row->checkin();
     $row->updateOrder("type='" . $_CB_database->getEscaped($row->type) . "' AND ordering > -10000 AND ordering < 10000 ");
     switch ($task) {
         case 'applyPlugin':
             $msg = sprintf(CBTxt::T('Successfully Saved changes to Plugin: %s'), $row->name);
             cbRedirect($_CB_framework->backendUrl("index.php?option={$option}&task=editPlugin&cid={$row->id}"), $msg);
         case 'savePlugin':
         default:
             $msg = sprintf(CBTxt::T('Successfully Saved Plugin: %s'), $row->name);
             cbRedirect($_CB_framework->backendUrl("index.php?option={$option}&task=showPlugins"), $msg);
             break;
     }
 }
	/**
	* Saves the CB plugin params after an edit form submit
	*/
	function savePluginParams( $option, $task ) {
		global $_CB_framework, $_CB_database, $_POST;
	
		if ( isset( $_POST['params'] ) ) {
		 	$_POST['params']	=	cbParamsEditorController::getRawParamsMagicgpcEscaped( $_POST['params'] );
		} else {
			$_POST['params']	=	null;
		}
	
		$row = new moscomprofilerPlugin( $_CB_database );
		if (!$row->bind( $_POST )) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
		if (!$row->check()) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
		if (!$row->store()) {
			echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}
		$row->checkin();
	
		$row->updateOrder( "type='".$_CB_database->getEscaped($row->type)."' AND ordering > -10000 AND ordering < 10000 " );
	
		switch ( $task ) {
			case 'applyPlugin':
				$msg = sprintf(CBTxt::T('Successfully Saved changes to Plugin: %s'), $row->name);
				cbRedirect( $_CB_framework->backendUrl( "index.php?option=$option&task=editPlugin&cid=$row->id" ), $msg );
	
			case 'savePlugin':
			default:
				$msg = sprintf(CBTxt::T('Successfully Saved Plugin: %s'), $row->name);
				cbRedirect( $_CB_framework->backendUrl( "index.php?option=$option&task=showPlugins" ), $msg );
				break;
		}
	}
	/**
	 * save config
	 *
	 * @param array  $config
	 */
	private function saveConfig( $config, $user, $plugin ) {
		global $_CB_database;

		$row			=	new moscomprofilerPlugin( $_CB_database );

		if ( $plugin->id ) {
			$row->load( $plugin->id );
		}

		$params			=	cbgjClass::parseParams( $config, true );

		$row->params	=	trim( $params->toIniString() );

		if ( $row->getError() || ( ! $row->store() ) ) {
			$this->showConfig( $user, $plugin, CBTxt::P( 'Config failed to save! Error: [error]', array( '[error]' => $row->getError() ) ) ); return;
		}

		cbgjClass::getPluginURL( array( 'config' ), CBTxt::T( 'Config saved successfully!' ), false, true );
	}