/**
  * Returns HTML for "install from discovery" tab
  * Used by Backend XML only
  * @deprecated Do not use directly, only for XML tabs backend
  *
  * @return string
  */
 public function displayDiscoveries()
 {
     global $_CB_framework, $_CB_database;
     // Prepare array of discovered plugins (not installed, but exists):
     $allPlgsFolders = array();
     $discoveredPlgs = array();
     $existingPlgList = array();
     $existingPlgFolders = array();
     $failingXmlFiles = array();
     // Discovers all installed plugins
     $query = 'SELECT ' . $_CB_database->NameQuote('folder') . ', ' . $_CB_database->NameQuote('type') . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_plugin');
     $_CB_database->setQuery($query);
     $existingPlgs = $_CB_database->loadAssocList();
     // Constructs list of installed plugins': 1) folders by type ($existingPlgList) and 2) list of installed folder paths ($existingPlgFolders)
     foreach ($existingPlgs as $existingPlg) {
         $plgType = $existingPlg['type'];
         $existingPlgList[$plgType][] = $existingPlg['folder'];
         $existingPlgFolders[] = $existingPlg['type'] . '/' . $existingPlg['folder'];
     }
     // Discovers inside each type all the directories:
     foreach ($existingPlgList as $plgType => $existingPlgs) {
         $plgFolders = array_filter(cbReadDirectory($_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' . $plgType), function ($subSubFolder) {
             return !in_array($subSubFolder, array('index.html', 'default'));
         });
         // Adds each directory of each type to the list of checks:
         foreach ($plgFolders as $plgFolder) {
             $plgFolderAndType = $plgType . '/' . $plgFolder;
             $allPlgsFolders[] = $plgFolderAndType;
             // Checks for sub-plugins, templates and known folders that might contain plugins:
             foreach (array('plugin', 'templates', 'processors', 'products') as $subFolder) {
                 $subfolderPath = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' . $plgFolderAndType . '/' . $subFolder;
                 if (file_exists($subfolderPath)) {
                     $subPluginsFolders = array_map(function ($subSubFolder) use($plgFolderAndType, $subFolder) {
                         return $plgFolderAndType . '/' . $subFolder . '/' . $subSubFolder;
                     }, array_filter(cbReadDirectory($subfolderPath), function ($subSubFolder) {
                         return !in_array($subSubFolder, array('index.html', 'default'));
                     }));
                     // Consolidates sub-folders:
                     $allPlgsFolders = array_merge($allPlgsFolders, $subPluginsFolders);
                 }
             }
         }
     }
     // As discoveries above might lead to multiple entries depending on database of installed plugins, makes discoveries unique:
     $allPlgsFolders = array_unique($allPlgsFolders);
     // Checks for each discovered folder if there are cbinstall-xml files, and if yes, if they are in the installed plugins list:
     foreach ($allPlgsFolders as $plgFolderAndType) {
         $plgFolderDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' . $plgFolderAndType;
         if (!is_file($plgFolderDir) && !in_array($plgFolderAndType, $existingPlgFolders)) {
             $plgFiles = cbReadDirectory($plgFolderDir);
             if ($plgFiles) {
                 foreach ($plgFiles as $plgFile) {
                     if (preg_match('/^.+\\.xml$/i', $plgFile)) {
                         $plgPath = $plgFolderDir . (substr($plgFolderDir, -1, 1) == '/' ? '' : '/') . $plgFile;
                         try {
                             $plgXml = @new SimpleXMLElement(trim(file_get_contents($plgPath)));
                             $elements = explode('/', $plgFolderAndType);
                             $lastFolder = array_pop($elements);
                             if ($plgXml->getName() == 'cbinstall' && $lastFolder != 'default' && !array_key_exists($plgFolderAndType, $discoveredPlgs)) {
                                 $discoveredPlgs[$plgFolderAndType] = array('name' => isset($plgXml->name) ? (string) $plgXml->name : $plgFolderAndType, 'file' => $plgFolderAndType);
                             }
                         } catch (\Exception $e) {
                             $failingXmlFiles[] = $plgPath;
                         }
                     }
                 }
             }
         }
     }
     $return = '';
     if (count($failingXmlFiles) > 0) {
         $return .= '<div class="col-sm-12">' . '<div class="col-sm-12 alert alert-danger" role="alert">' . '<h4>' . CBTxt::Th('Malformed XML files discovered in CB plugin folders:') . '</h4>';
         foreach ($failingXmlFiles as $failedFilePath) {
             $return .= '<div class="cbft_text form-group cb_form_line clearfix">' . CBTxt::Th('XML_FILE_FILE_IS_MALFORMED', 'XML file [FILE_PATH_AND_NAME] is malformed and should be replaced or fixed, or the plugin should be removed', array('[FILE_PATH_AND_NAME]' => '<strong>' . htmlspecialchars($failedFilePath) . '</strong>')) . '</div>';
         }
         $return .= '</div>' . '</div>';
     }
     if ($discoveredPlgs) {
         foreach ($discoveredPlgs as $discoveredPlg) {
             $return .= '<div class="cbft_text form-group cb_form_line clearfix">' . '<div class="control-label col-sm-3">' . htmlspecialchars($discoveredPlg['name']) . '</div>' . '<div class="cb_field col-sm-9">' . '<input type="button" class="btn btn-primary btn-sm" value="' . htmlspecialchars(CBTxt::T('Install Package')) . '" onclick="submitbutton( \'act=apply&amp;func=installPluginDisc&amp;plgfile=' . addslashes($discoveredPlg['file']) . '\' )" />' . '</div>' . '</div>';
         }
     } else {
         $return .= '<div class="col-sm-12">' . CBTxt::Th('No plugins discovered.') . '</div>';
     }
     return $return;
 }
 /**
  * Reads the files and directories in a directory
  * Backend-only
  *
  * @access private
  *
  * @param  string   $path      The file system path
  * @param  string   $filter    A filter for the names
  * @param  boolean  $recurse   Recurse search into sub-directories
  * @param  boolean  $fullpath  True if to prepend the full path to the file name
  * @return array               List of files
  */
 function cbReadDirectory($path, $filter = '.', $recurse = false, $fullpath = false)
 {
     $arr = array();
     if (!@is_dir($path)) {
         return $arr;
     }
     $handle = opendir($path);
     while (true == ($file = readdir($handle))) {
         if (!in_array($file, array('.', '..', '.svn', '.git', '.gitignore', '.gitattributes', '__MACOSX'))) {
             $dir = _cbPathName($path . '/' . $file, false);
             if (preg_match("/{$filter}/", $file)) {
                 if ($fullpath) {
                     $arr[] = trim(_cbPathName($path . '/' . $file, false));
                 } else {
                     $arr[] = trim($file);
                 }
             }
             if ($recurse && is_dir($dir)) {
                 $arr2 = cbReadDirectory($dir, $filter, $recurse, $fullpath);
                 if (!$fullpath) {
                     foreach ($arr2 as $k => $n) {
                         $arr2[$k] = $file . '/' . $n;
                     }
                 }
                 $arr = array_merge($arr, $arr2);
             }
         }
     }
     closedir($handle);
     asort($arr);
     return $arr;
 }
Exemple #3
0
	/**
	* @param string The name of the form element
	* @param string The value of the element
	* @param CBSimpleXMLElement  $node The xml element for the parameter
	* @param string The control name
	* @return string The html for the element
	*/
	function _form_imagelist( $name, $value, &$node, $control_name ) {
		global $_CB_framework;

		// path to images directory
		$path = $_CB_framework->getCfg('absolute_path') . $node->attributes( 'directory' );
		$files = cbReadDirectory( $path, '\.png$|\.gif$|\.jpg$|\.bmp$|\.ico$' );

		$options = array();
		foreach ($files as $file) {
			$options[] = moscomprofilerHTML::makeOption( $file, $file );
		}
		if ( !$node->attributes( 'hide_none' ) ) {
			array_unshift( $options, moscomprofilerHTML::makeOption( '-1', '- Do not use an image -' ) );
		}
		if ( !$node->attributes( 'hide_default' ) ) {
			array_unshift( $options, moscomprofilerHTML::makeOption( '', '- Use Default image -' ) );
		}

		return moscomprofilerHTML::selectList( $options, ''. $this->control_name( $control_name, $name ) . '', 'class="inputbox" id="' . $this->control_id( $control_name, $name ) . '"', 'value', 'text', $value, 2, true, false );
	}
function finishInstallation($option)
{
    global $_CB_framework, $ueConfig, $task;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    _CBsecureAboveForm('finishInstallation');
    $tgzFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/pluginsfiles.tgz';
    $installerFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/';
    if (file_exists($installerFile . 'comprofiler.xml')) {
        $installerFile .= 'comprofiler.xml';
    } elseif (file_exists($installerFile . 'comprofilej.xml')) {
        $installerFile .= 'comprofilej.xml';
    } elseif (file_exists($installerFile . 'comprofileg.xml')) {
        $installerFile .= 'comprofileg.xml';
    }
    if (!file_exists($tgzFile)) {
        echo CBTxt::T('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!');
        return;
    }
    $installer = new cbInstallerPlugin();
    $client = 2;
    // Check that the zlib is available
    if (!extension_loaded('zlib')) {
        cbInstaller::renderInstallMessage(CBTxt::T('The installer cannot continue before zlib is installed'), CBTxt::T('Installer - Error'), $installer->returnTo($option, $task, $client));
        return;
    }
    if (!$installer->upload($tgzFile, true, false)) {
        cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Uncompressing %s failed.'), $tgzFile), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        return;
    }
    $adminFS = cbAdminFileSystem::getInstance();
    $installFrom = $installer->installDir();
    $filesList = cbReadDirectory($installFrom, '.', true);
    // check if core directories exist as are needed to install plugins:
    $baseDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler';
    if (!$adminFS->is_dir($baseDir . '/plugin')) {
        if (!$adminFS->mkdir($baseDir . '/plugin')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/language')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/language')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/language'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/language/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/language/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/templates')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/templates')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/templates'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/templates/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/templates/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/user')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/user')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/user'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/user/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/user/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    // install core plugins:
    foreach ($filesList as $file) {
        if (preg_match('/^.+\\.xml$/i', $file)) {
            $plgPath = $installFrom . (substr($installFrom, -1, 1) == '/' ? '' : '/') . $file;
            $plgXml = new \CBLib\Xml\SimpleXMLElement(trim(file_get_contents($plgPath)));
            if ($plgXml->getName() == 'cbinstall') {
                $plgDir = dirname($plgPath) . '/';
                $plgInstaller = new cbInstallerPlugin();
                if (!$plgInstaller->install($plgDir)) {
                    cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Installing plugin failed with error: %s : %s'), $plgInstaller->i_elementname ? $plgInstaller->i_elementname : $file, $plgInstaller->getError()), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
                    return;
                }
            }
        }
    }
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        cbInstaller::renderInstallMessage(CBTxt::T('Deleting expanded tgz file directory failed with an error.'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    $tgzFileOS = _cbPathName($tgzFile, false);
    $result = $adminFS->unlink($tgzFileOS);
    if ($result === false) {
        cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Deleting file %s failed with an error.'), $tgzFileOS), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    // adapt published fields to global CB config (regarding name type)
    _cbAdaptNameFieldsPublished($ueConfig);
    $htmlToDisplay = $_CB_framework->getUserState('com_comprofiler_install');
    // clears the session buffer memory after installaion done:
    $_CB_framework->setUserState('com_comprofiler_install', '');
    $installerXml = new SimpleXMLElement(file_get_contents($installerFile));
    if (is_object($installerXml)) {
        $description = $installerXml->getElementByPath('description');
        if ($description !== false) {
            echo '<h2>' . $description->data() . '</h2>';
        }
    }
    echo $htmlToDisplay;
    echo '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::Th('Installation done.') . '</div>' . '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::Th('Now is a great time to checkout the <a href="[help_url]" target="_blank">Getting Started</a> resources.', null, array('[help_url]' => 'http://www.joomlapolis.com/documentation/community-builder/getting-started?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen')) . '</div>' . '<div style="margin-bottom:10px;">' . '<div style="font-size:12px;"><a href="http://www.joomlapolis.com/cb-solutions?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen" target="_blank">' . CBTxt::Th('Click here to see more CB Plugins (Languages, Fields, Tabs, Signup-Connect, Paid Memberships and over 30 more) by CB Team at joomlapolis.com') . '</a></div>' . '<div style="font-size:12px;"><a href="http://extensions.joomla.org/extensions/clients-a-communities/communities/210" target="_blank">' . CBTxt::Th('Click here to see our CB listing on the Joomla! Extensions Directory (JED) and find third-party add-ons for your website.') . '</a></div>' . '<div style="font-size:12px;margin:10px 0 25px;">or &nbsp; <a href="index.php?option=com_comprofiler&view=showconfig" class="btn btn-primary">' . CBTxt::Th('Start to Configure Community Builder') . '</a></div>' . '</div>';
    $_CB_framework->setUserState("com_comprofiler_install", '');
}
	/**
	 * Implements a form field to select a folder from a list
	 *
	 * @param  string              $name          The name of the form element
	 * @param  string              $value         The value of the element
	 * @param  SimpleXMLElement  $node          The xml element for the parameter
	 * @param  string              $control_name  The control name
	 * @return string                             The html for the element
	 */
	function _form_filelist( $name, $value, &$node, $control_name ) {
		global $_CB_framework;

		$size							=	0;
		$cols							=	$node->attributes( 'cols' );
		$rows							=	$node->attributes( 'rows' );
		$multi							=	( $node->attributes( 'multiple' ) == 'true' );
		$translate						=	$node->attributes( 'translate' );

		if ( $this->_view ) {
			if ( $value === null ) {
				$selected				=	array();
			} else {
				if ( $multi && ( ! is_array( $value ) ) ) {
					$selected			=	explode( '|*|', $value );
				} else {
					$selected			=	array( $value );
				}
			}

			$contentOptions				=	$this->_list_options_selected( $name, $node, $control_name, $node->children(), $selected );
			$contentTexts				=	array();
			$contentValues				=	array();

			foreach ( $contentOptions as $contentOption ) {
				$contentValues[]		=	$contentOption->value;
				$contentTexts[]			=	htmlspecialchars( $contentOption->text );
			}

			foreach ( $selected as $v ) {
				if ( ! in_array( $v, $contentValues ) ) {
					if ( $translate == 'no' ) {
						$contentTexts[]	=	htmlspecialchars( $v );
					} else {
						$contentTexts[]	=	htmlspecialchars( CBTxt::T( $v ) );
					}
				}
			}

			if ( count( $contentTexts ) > 0 ) {
				if ( $cols || $rows ) {
					$content			=	moscomprofilerHTML::list2Table( $contentTexts, $cols, $rows, $size );
				} else {
					$content			=	implode( ', ', $contentTexts );
				}
			} else {
				$content				=	' - ';
			}

			return $content;
		} else {
			$type						=	$node->attributes( 'type' );
			$directory					=	$node->attributes( 'directory' );
			$recurse					=	( $node->attributes( 'recurse' ) == 'true' );

			if ( $type == 'folderlist' ) {
				$filter					=	'^[^.]+$';
			} elseif ( $type == 'imagelist' ) {
				$filter					=	'\.png$|\.gif$|\.jpg$|\.bmp$|\.ico$';
			} else {
				$filter					=	$node->attributes( 'filter' );

				if ( ! $filter ) {
					$filter				=	'.';
				}
			}

			$this->substituteName( $directory, false );

			$path						=	( $directory && ( $directory[0] == '/' ) ? $_CB_framework->getCfg( 'absolute_path' ) . $directory : $directory );
			$files						=	cbReadDirectory( $path, $filter, $recurse );
			$options					=	array();

			if ( is_array( $value ) ) {
				$value					=	implode( '|*|', $value );
			}

			$defaults					=	array();

			if ( $type == 'imagelist' ) {
				if ( ! $node->attributes( 'hide_default' ) ) {
					$defaults			=	array( '', '--- ' . CBTxt::T( 'Use Default image' ) . ' ---' );
				}

				if ( ! $node->attributes( 'hide_none' ) ) {
					$options[]			=	moscomprofilerHTML::makeOption( '-1', '--- ' . CBTxt::T( 'Do not use an image' ) . ' ---' );
				}
			}

			$this->_list_options_default( $node, $options, $value, $defaults );
			$this->_list_options( $name, $node, $control_name, $options, $node->children(), true, $value );
			$this->_list_options_data( $node, $options, $files );

			$selected					=	explode( '|*|', $value );

			return $this->selectList( $options, $node, $control_name, $name, $selected, $multi );
		}
	}
 /**
  * plugin uninstaller with best effort depending on what it finds.
  *
  * @param  int     $id
  * @param  string  $option
  * @param  int     $client
  * @param  string  $action
  * @return boolean
  */
 function uninstall($id, $option, $client = 0)
 {
     global $_CB_database;
     $db = false;
     if ($this->checkPluginGetXml($id, $option, $client)) {
         if ($this->i_xmldocument !== null && count($this->i_xmldocument->children()) > 0) {
             $cbInstallXML =& $this->i_xmldocument;
             // get the element name:
             $e =& $cbInstallXML->getElementByPath('name');
             $this->elementName($e->data());
             // $cleanedElementName = strtolower(str_replace(array(" ","."),array("","_"),$this->elementName()));
             // get the files element
             $files_element =& $cbInstallXML->getElementByPath('files');
             if ($files_element) {
                 if (count($files_element->children())) {
                     foreach ($files_element->children() as $file) {
                         if ($file->attributes("plugin")) {
                             $this->elementSpecial($file->attributes("plugin"));
                             break;
                         }
                     }
                     $cleanedMainFileName = strtolower(str_replace(array(" ", "."), array("", "_"), $this->elementSpecial()));
                 }
                 // Is there an uninstallfile
                 $uninstallfile_elemet =& $cbInstallXML->getElementByPath('uninstallfile');
                 if ($uninstallfile_elemet !== false) {
                     if (is_file($this->i_elementdir . $uninstallfile_elemet->data())) {
                         global $_PLUGINS;
                         // needed for the require_once below !
                         require_once $this->i_elementdir . $uninstallfile_elemet->data();
                         $ret = call_user_func_array("plug_" . $cleanedMainFileName . "_uninstall", array());
                         if ($ret != '') {
                             $this->setError(0, $ret);
                         }
                     }
                 }
                 $adminFS =& cbAdminFileSystem::getInstance();
                 foreach ($files_element->children() as $file) {
                     // delete the files
                     $filename = $file->data();
                     if (file_exists($this->i_elementdir . $filename)) {
                         $parts = pathinfo($filename);
                         $subpath = $parts['dirname'];
                         if ($subpath != '' && $subpath != '.' && $subpath != '..') {
                             //echo '<br />'. 'Deleting'  .': '. $this->i_elementdir . $subpath;
                             $result = $adminFS->deldir(_cbPathName($this->i_elementdir . $subpath . '/'));
                         } else {
                             //echo '<br />'. 'Deleting'  .': '. $this->i_elementdir . $filename;
                             $result = $adminFS->unlink(_cbPathName($this->i_elementdir . $filename, false));
                         }
                         //echo intval( $result );
                     }
                 }
                 // Are there any SQL queries??
                 $query_element =& $cbInstallXML->getElementByPath('uninstall/queries');
                 if ($query_element !== false) {
                     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));
                             return false;
                         }
                     }
                 }
                 // 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, $cleanedMainFileName, 'drop', 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());
                         return false;
                     }
                 }
                 // Delete tabs and private fields of plugin:
                 $this->deleteTabAndFieldsOfPlugin($id);
                 // remove XML file from front
                 $xmlRemoveResult = $adminFS->unlink(_cbPathName($this->i_installfilename, false));
                 $filesRemoveResult = true;
                 /*					// define folders that should not be removed
                 					$sysFolders = array(
                 					'content',
                 					'search'
                 					);
                 					if ( ! in_array( $row->folder, $sysFolders ) ) {
                 */
                 // delete the non-system folders if empty
                 if (count(cbReadDirectory($this->i_elementdir)) < 1) {
                     $filesRemoveResult = $adminFS->deldir($this->i_elementdir);
                 }
                 /*					}
                 */
                 if (!$xmlRemoveResult) {
                     HTML_comprofiler::showInstallMessage('Could not delete XML file: ' . _cbPathName($this->i_installfilename, false) . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
                 }
                 if (!$filesRemoveResult) {
                     HTML_comprofiler::showInstallMessage('Could not delete directory: ' . $this->i_elementdir . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
                 }
             }
         }
         $_CB_database->setQuery("DELETE FROM #__comprofiler_plugin WHERE id = " . (int) $id);
         if (!$_CB_database->query()) {
             $msg = $_CB_database->stderr;
             HTML_comprofiler::showInstallMessage('Cannot delete plugin database entry due to error: ' . $msg, 'Uninstall -  error', $this->returnTo($option, 'showPlugins'));
             return false;
         }
         if ($this->i_xmldocument !== null && $db !== false && count($db->children()) > 0) {
             HTML_comprofiler::fixcbdbShowResults($sqlUpgrader, true, false, $success, array(), array(), $this->elementName(), 1, false);
         }
         return true;
     }
     return false;
 }
function finishInstallation($option)
{
    global $_CB_framework, $ueConfig, $task;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    HTML_comprofiler::secureAboveForm('finishInstallation');
    $tgzFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/pluginsfiles.tgz';
    $installerFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/';
    if (file_exists($installerFile . 'comprofiler.xml')) {
        $installerFile .= 'comprofiler.xml';
    } elseif (file_exists($installerFile . 'comprofilej.xml')) {
        $installerFile .= 'comprofilej.xml';
    } elseif (file_exists($installerFile . 'comprofileg.xml')) {
        $installerFile .= 'comprofileg.xml';
    }
    if (!file_exists($tgzFile)) {
        echo _UE_NOT_AUTHORIZED;
        return;
    }
    $installer = new cbInstallerPlugin();
    $client = 2;
    // Check that the zlib is available
    if (!extension_loaded('zlib')) {
        HTML_comprofiler::showInstallMessage(CBTxt::T('The installer cannot continue before zlib is installed'), CBTxt::T('Installer - Error'), $installer->returnTo($option, $task, $client));
        exit;
    }
    if (!$installer->upload($tgzFile, true, false)) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Uncompressing %s failed."), $tgzFile), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    $installFrom = $installer->installDir();
    $installTo = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin';
    $filesList = cbReadDirectory($installFrom, '.', true);
    // create directories and remove them from file list:
    if (!$installer->mosMakePath(dirname($installTo) . '/', 'plugin')) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $installTo . '/plugin'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    foreach ($filesList as $k => $file) {
        if (basename($file) != $file) {
            $newdir = dirname($file);
            if (!$installer->mosMakePath($installTo . '/', $newdir)) {
                HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $installTo . '/' . $newdir), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
                exit;
            }
        }
        if (!is_file($installFrom . '/' . $file)) {
            unset($filesList[$k]);
        }
    }
    $result = $installer->copyFiles($installFrom, $installTo, $filesList, true);
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Copying plugin files failed with error: %s"), $installer->getError()), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    $adminFS =& cbAdminFileSystem::getInstance();
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(CBTxt::T('Deleting expanded tgz file directory failed with an error.'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    $tgzFileOS = _cbPathName($tgzFile, false);
    $result = $adminFS->unlink($tgzFileOS);
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Deleting file %s failed with an error."), $tgzFileOS), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    // adapt published fields to global CB config (regarding name type)
    _cbAdaptNameFieldsPublished($ueConfig);
    $htmlToDisplay = $_CB_framework->getUserState('com_comprofiler_install');
    // clears the session buffer memory after installaion done:
    $_CB_framework->setUserState('com_comprofiler_install', '');
    cbimport('cb.xml.simplexml');
    $installerXml = new CBSimpleXMLElement(file_get_contents($installerFile));
    if (is_object($installerXml)) {
        $description = $installerXml->getElementByPath('description');
        if ($description !== false) {
            echo '<h2>' . $description->data() . '</h2>';
        }
    }
    echo $htmlToDisplay;
    ?>
<div style="font-weight:bold;font-size:110%;background:#ffffe4;border:2px green solid;padding:5px;margin-bottom:20px;"><font color="green"><?php 
    echo CBTxt::T('Second and last installation step of Community Builder Component (comprofiler) done successfully.');
    ?>
</font></div><br />
<div style="font-weight:bold;font-size:125%;background:#ffffe4;border:2px green solid;padding:5px;">
<font color="green"><b><?php 
    echo CBTxt::T('Installation finished. Important: Please read README.TXT and installation manual for further settings.');
    ?>
 <br /><br /><?php 
    echo CBTxt::T('We also have a PDF installation guide as well as a complete documentation available on');
    ?>
 <a href="http://www.joomlapolis.com">www.joomlapolis.com</a> <?php 
    echo CBTxt::T('which will help you making the most out of your Community Builder installation, while supporting this project, as well as plugins and templates.');
    ?>
</b></font>
</div>
<?php 
    $_CB_framework->setUserState("com_comprofiler_install", '');
}
function plug_cbgallery_install()
{
	global $_CB_framework, $_CB_database;

	$plugin								=	new PluginTable();

	if ( $plugin->load( array( 'element' => 'cb.profilegallery' ) ) ) {
		$path							=	$_CB_framework->getCfg( 'absolute_path' );
		$indexPath						=	$path . '/components/com_comprofiler/plugin/user/plug_cbgallery/index.html';
		$oldFilesPath					=	$path . '/images/comprofiler/plug_profilegallery';
		$newFilesPath					=	$path . '/images/comprofiler/plug_cbgallery';

		$query							=	'SELECT *'
										.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plug_profilegallery' );
		$_CB_database->setQuery( $query );
		$rows							=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__comprofiler_plug_profilegallery', 'id' ) );

		/** @var $rows Table[] */
		foreach ( $rows as $row ) {
			$oldFilePath				=	$oldFilesPath . '/' . (int) $row->get( 'userid' );

			if ( in_array( $row->get( 'pgitemtype' ), array( 'jpg', 'jpeg', 'gif', 'png' ) ) ) {
				$type					=	'photos';
			} else {
				$type					=	'files';
			}

			$newFilePath				=	$newFilesPath . '/' . (int) $row->get( 'userid' ) . '/' . $type;

			if ( ( ! file_exists( $oldFilePath . '/' . $row->get( 'pgitemfilename' ) ) ) || ( ( $type == 'photos' ) && ( ! file_exists( $oldFilePath . '/tn' . $row->get( 'pgitemfilename' ) ) ) ) ) {
				continue;
			}

			$cleanFileName				=	str_replace( 'pg_', '', pathinfo( $row->get( 'pgitemfilename' ), PATHINFO_FILENAME ) );
			$newFileName				=	uniqid( $cleanFileName . '_' ) . '.' . strtolower( pathinfo( $row->get( 'pgitemfilename' ), PATHINFO_EXTENSION ) );

			if ( cbReadDirectory( $newFilePath, '^' . preg_quote( $cleanFileName ) ) ) {
				$query					=	'SELECT COUNT(*)'
										.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_gallery_items' )
										.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $row->get( 'userid' )
										.	"\n AND " . $_CB_database->NameQuote( 'value' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $cleanFileName, true ) . '%', false );
				$_CB_database->setQuery( $query );
				if ( $_CB_database->loadResult() ) {
					continue;
				}
			}

			if ( ! is_dir( $newFilesPath ) ) {
				$oldMask				=	@umask( 0 );

				if ( @mkdir( $newFilesPath, 0755, true ) ) {
					@umask( $oldMask );
					@chmod( $newFilesPath, 0755 );

					if ( ! file_exists( $newFilesPath . '/index.html' ) ) {
						@copy( $indexPath, $newFilesPath . '/index.html' );
						@chmod( $newFilesPath . '/index.html', 0755 );
					}
				} else {
					@umask( $oldMask );
				}
			}

			if ( ! file_exists( $newFilesPath . '/.htaccess' ) ) {
				file_put_contents( $newFilesPath . '/.htaccess', 'deny from all' );
			}

			if ( ! is_dir( $newFilePath ) ) {
				$oldMask				=	@umask( 0 );

				if ( @mkdir( $newFilePath, 0755, true ) ) {
					@umask( $oldMask );
					@chmod( $newFilePath, 0755 );

					if ( ! file_exists( $newFilePath . '/index.html' ) ) {
						@copy( $indexPath, $newFilePath . '/index.html' );
						@chmod( $newFilePath . '/index.html', 0755 );
					}
				} else {
					@umask( $oldMask );
				}
			}

			if ( ! @copy( $oldFilePath . '/' . $row->get( 'pgitemfilename' ), $newFilePath . '/' . $newFileName ) ) {
				continue;
			} else {
				@chmod( $newFilePath . '/' . $newFileName, 0755 );
			}

			if ( $type == 'photos' ) {
				if ( ! @copy( $oldFilePath . '/tn' . $row->get( 'pgitemfilename' ), $newFilePath . '/tn' . $newFileName ) ) {
					continue;
				} else {
					@chmod( $newFilePath . '/tn' . $newFileName, 0755 );
				}
			}

			$item						=	new Table( null, '#__comprofiler_plugin_gallery_items', 'id' );

			$item->set( 'user_id', (int) $row->get( 'userid' ) );
			$item->set( 'type', $type );
			$item->set( 'value', $newFileName );
			$item->set( 'folder', 0 );
			$item->set( 'title', $row->get( 'pgitemtitle' ) );
			$item->set( 'description', $row->get( 'pgitemdescription' ) );
			$item->set( 'date', $row->get( 'pgitemdate' ) );
			$item->set( 'published', ( $row->get( 'pgitemapproved', 0 ) ? (int) $row->get( 'pgitempublished', 0 ) : -1 ) );

			if ( ! $item->store() ) {
				@unlink( $newFilePath . '/' . $newFileName );

				if ( $type == 'photos' ) {
					@unlink( $newFilePath . '/tn' . $newFileName );
				}
			}
		}

		$field							=	new FieldTable();

		if ( $field->load( array( 'name' => 'cb_pgtotalquotaitems' ) ) ) {
			$field->set( 'type', 'integer' );
			$field->set( 'tabid', 11 );
			$field->set( 'pluginid', 1 );
			$field->set( 'readonly', 1 );
			$field->set( 'calculated', 0 );
			$field->set( 'sys', 0 );

			$field->store();
		}

		$gallery						=	new PluginTable();

		if ( $gallery->load( array( 'element' => 'cbgallery' ) ) ) {
			$galleryParams				=	new Registry( $gallery->params );

			$galleryParams->set( 'photos_item_limit', 'cb_pgtotalquotaitems' );
			$galleryParams->set( 'files_item_limit', 'cb_pgtotalquotaitems' );

			$gallery->set( 'params', $galleryParams->asJson() );

			$gallery->store();
		}

		ob_start();
		$plgInstaller					=	new cbInstallerPlugin();

		$plgInstaller->uninstall( $plugin->id, 'com_comprofiler' );
		ob_end_clean();
	}
}
Exemple #9
0
 /**
  * Renders as ECHO HTML code
  *
  * @param  SimpleXMLElement  $modelView
  * @param  array             $modelRows
  * @param  DrawController    $controllerView
  * @param  array             $options
  * @return void
  */
 protected function renderMenuGroup(&$modelView, &$modelRows, &$controllerView, $options)
 {
     global $_PLUGINS;
     $htmlFormatting = 'span';
     if (count($this->_controllerModel->children()) > 0) {
         //TBD: not needed yet, but kept if needed    $this->_applyStylingToMeAndChildren( $this->_controllerModel, $this->styling );
         echo $this->renderMenuGroupHeader($this->_controllerModel, $htmlFormatting);
         foreach ($this->_controllerModel->children() as $child) {
             /** @var $child SimpleXMLElement */
             // Check if ACL authorizes to view and to use that menu:
             if (!Access::authorised($child)) {
                 continue;
             }
             if ($child->getName() == 'menu') {
                 // Check if ACL authorizes to use the action linked by that menu:
                 if (!$this->authorised($child)) {
                     continue;
                 }
                 $menuName = $child->attributes('name');
                 echo $this->renderMenu($child, $modelRows[$menuName], $controllerView, $options, $htmlFormatting);
             } elseif ($child->getName() == 'showview') {
                 $showviewType = $child->attributes('type');
                 if ($showviewType == 'plugins') {
                     $groups = explode(',', $child->attributes('groups'));
                     $action = $child->attributes('action');
                     $path = $child->attributes('path');
                     foreach ($groups as $group) {
                         $matches = null;
                         if (preg_match('/^([^\\[]+)\\[(.+)\\]$/', $group, $matches)) {
                             $classId = $matches[2];
                             $group = $matches[1];
                         } else {
                             $classId = null;
                         }
                         $_PLUGINS->loadPluginGroup($group, $classId, 0);
                         $loadedPlugins = $_PLUGINS->getLoadedPluginGroup($group);
                         foreach ($loadedPlugins as $plugin) {
                             $element = $_PLUGINS->loadPluginXML('action', $action, $plugin->id);
                             $viewModel = $element->getElementByPath($path);
                             if ($viewModel) {
                                 foreach ($viewModel->children() as $extChild) {
                                     /** @var $extChild SimpleXMLElement */
                                     if ($extChild->getName() == 'menu') {
                                         // Check if ACL authorizes to use the action linked by that menu:
                                         if (!$this->authorised($extChild)) {
                                             continue;
                                         }
                                         $menuName = $extChild->attributes('name');
                                         echo $this->renderMenu($extChild, $modelRows[$menuName], $controllerView, $options, $htmlFormatting);
                                     }
                                 }
                             }
                         }
                     }
                 } elseif ($showviewType == 'xml') {
                     // e.g.: <showview name="gateway_paymentstatus_information" mode="view" type="xml" file="processors/{payment_method}/edit.gateway" path="/*/views/view[@name=&quot;paymentstatusinformation&quot;]" mandatory="false" />
                     $fromNode = $child->attributes('path');
                     $fromFile = $child->attributes('file');
                     $mandatory = $child->attributes('mandatory');
                     if ($fromNode && $fromFile !== null) {
                         // $this->substituteName( $fromFile, true );
                         // $this->substituteName( $fromNode, false );
                         if ($fromFile !== '') {
                             $fromFile = RegistryEditView::pathFromXML($fromFile . '.xml', $child, $this->_pluginObject);
                         }
                         if (strpos($fromFile, '/*/') !== false) {
                             $parts = explode('/*/', $fromFile);
                             $fromFiles = cbReadDirectory($parts[0], '.', false, true);
                             // '^' . preg_quote( $subparts[0], '/' ) . '$'
                         } else {
                             $parts = null;
                             $fromFiles = array($fromFile);
                         }
                         foreach ($fromFiles as $fromDirOrFile) {
                             $viewModel = null;
                             if ($fromDirOrFile === '') {
                                 $viewModel = $this->_views->xpath($fromNode);
                             } else {
                                 if (!isset($parts) || is_dir($fromDirOrFile)) {
                                     $fromDirOrFile = $fromDirOrFile . (isset($parts[1]) ? '/' . $parts[1] : '');
                                     if (file_exists($fromDirOrFile)) {
                                         $fromRoot = new SimpleXMLElement($fromDirOrFile, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0), true);
                                         $viewModel = $fromRoot->xpath($fromNode);
                                     }
                                 } else {
                                     continue;
                                 }
                             }
                             if ($viewModel && count($viewModel)) {
                                 foreach ($viewModel[0]->children() as $extChild) {
                                     /** @var $extChild SimpleXMLElement */
                                     if ($extChild->getName() == 'menu') {
                                         // Check if ACL authorizes to use the action linked by that menu:
                                         if (!$this->authorised($extChild)) {
                                             continue;
                                         }
                                         $menuName = $extChild->attributes('name');
                                         echo $this->renderMenu($extChild, $modelRows[$menuName], $controllerView, $options, $htmlFormatting);
                                     }
                                 }
                             } elseif ($mandatory == 'false') {
                                 continue;
                             } else {
                                 trigger_error('MenuController:showview: View file ' . $fromDirOrFile . ', path: ' . $fromNode . ' does not exist or is empty.', E_USER_NOTICE);
                             }
                         }
                     }
                 }
             }
         }
         echo $this->renderMenuGroupFooter($this->_controllerModel, $htmlFormatting);
     }
 }
 /**
  * Plugin un-installer with best effort depending on what it finds.
  *
  * @param  int      $pluginId  Plugin id to uninstall
  * @param  string   $option    Option request of component
  * @return boolean             Success
  */
 function uninstall($pluginId, $option)
 {
     global $_CB_framework, $_CB_database;
     $db = false;
     $success = false;
     if (!$this->checkPluginGetXml($pluginId, $option)) {
         return false;
     }
     if ($this->i_xmldocument !== null && count($this->i_xmldocument->children()) > 0) {
         $cbInstallXML = $this->i_xmldocument;
         // get the element name:
         $e = $cbInstallXML->getElementByPath('name');
         $this->elementName($e->data());
         // $cleanedElementName = strtolower(str_replace(array(" ","."),array("","_"),$this->elementName()));
         // get the files element
         $files_element = $cbInstallXML->getElementByPath('files');
         if ($files_element !== false) {
             if (count($files_element->children())) {
                 foreach ($files_element->children() as $file) {
                     if ($file->attributes("plugin")) {
                         $this->elementSpecial($file->attributes("plugin"));
                         break;
                     }
                 }
             }
             $cleanedMainFileName = strtolower(str_replace(array(" ", "."), array("", "_"), $this->elementSpecial()));
             // Is there an uninstallfile
             $uninstallfile_elemet = $cbInstallXML->getElementByPath('uninstallfile');
             if ($uninstallfile_elemet !== false) {
                 if (is_file($this->i_elementdir . $uninstallfile_elemet->data())) {
                     global $_PLUGINS;
                     // needed for the require_once below !
                     /** @noinspection PhpIncludeInspection */
                     require_once $this->i_elementdir . $uninstallfile_elemet->data();
                     $ret = call_user_func_array("plug_" . $cleanedMainFileName . "_uninstall", array());
                     if ($ret != '') {
                         $this->setError(0, $ret);
                     }
                 }
             }
             $adminFS = cbAdminFileSystem::getInstance();
             $installFileName = basename($this->i_installfilename);
             $this->deleteFiles($files_element, $adminFS, $installFileName);
             // Are there any CBLib libraries ?
             $libraries_element = $cbInstallXML->getElementByPath('libraries');
             if ($libraries_element !== false) {
                 foreach ($libraries_element->children() as $library) {
                     if ($library->getName() != 'library') {
                         continue;
                     }
                     // Delete files from library package:
                     $savePackage = $this->i_xmldocument;
                     $subFolder = $library->attributes('name');
                     $saveElement = $this->elementDir();
                     $this->elementDir($_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/libraries/' . ($subFolder ? $subFolder . '/' : null));
                     $this->i_xmldocument = $library;
                     $this->deleteFiles($library->getElementByPath('files'), $adminFS, null);
                     $this->i_xmldocument = $savePackage;
                     $this->elementDir($saveElement);
                 }
             }
             // Are there any SQL queries??
             $query_element = $cbInstallXML->getElementByPath('uninstall/queries');
             if ($query_element !== false) {
                 foreach ($query_element->children() as $query) {
                     $_CB_database->setQuery(trim($query->data()));
                     if (!$_CB_database->query()) {
                         $this->setError(1, "SQL Error " . $_CB_database->getErrorMsg());
                         return false;
                     }
                 }
             }
             // Are there any Database statements ??
             $db = $cbInstallXML->getElementByPath('database');
             if ($db !== false && count($db->children()) > 0) {
                 $sqlUpgrader = new DatabaseUpgrade(null, false);
                 //$sqlUpgrader->setDryRun( true );
                 $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedMainFileName, 'drop', null, 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());
                     return false;
                 }
             }
             // Delete tabs and private fields of plugin:
             $this->deleteTabAndFieldsOfPlugin($pluginId);
             // remove XML file from front
             $xmlRemoveResult = $adminFS->unlink(_cbPathName($this->i_installfilename, false));
             $filesRemoveResult = true;
             /*					// define folders that should not be removed
             								$sysFolders = array(
             								'content',
             								'search'
             								);
             								if ( ! in_array( $row->folder, $sysFolders ) ) {
             				*/
             // delete the non-system folders if empty
             if (count(cbReadDirectory($this->i_elementdir)) < 1) {
                 $filesRemoveResult = $adminFS->deldir($this->i_elementdir);
             }
             /*					}
              */
             if (!$xmlRemoveResult) {
                 self::renderInstallMessage('Could not delete XML file: ' . _cbPathName($this->i_installfilename, false) . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
             }
             if (!$filesRemoveResult) {
                 self::renderInstallMessage('Could not delete directory: ' . $this->i_elementdir . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
             }
         }
     }
     $_CB_database->setQuery("DELETE FROM #__comprofiler_plugin WHERE id = " . (int) $pluginId);
     if (!$_CB_database->query()) {
         $msg = $_CB_database->getErrorMsg();
         self::renderInstallMessage('Cannot delete plugin database entry due to error: ' . $msg, 'Uninstall -  error', $this->returnTo($option, 'showPlugins'));
         return false;
     }
     if ($this->i_xmldocument !== null && $db !== false && count($db->children()) > 0) {
         CBDatabaseChecker::renderDatabaseResults($sqlUpgrader, true, false, $success, array(), array(), $this->elementName(), 1, false);
     }
     return true;
 }
	function editPluginSettingsParams( &$row, $option, $task, $uid, &$element, &$params, &$options ) {
		global $_CB_database, $_CB_framework;
	
		$lists 	= array();
	
		// get list of groups
		if ($row->access == 99 || $row->client_id == 1) {
			$lists['access'] = CBTxt::T('Administrator') . '<input type="hidden" name="access" value="99" />';
		} else {
			// build the html select list for the group access
			$accessTree		=	$_CB_framework->acl->get_access_children_tree();
			$lists['access'] = moscomprofilerHTML::selectList( $accessTree, 'access', 'class="inputbox" size="3"', 'value', 'text', intval( $row->access ), 2 );
		}
	
		if ($uid) {
			$row->checkout( $_CB_framework->myId() );
	
			if ( $row->ordering > -10000 && $row->ordering < 10000 ) {
				// build the html select list for ordering
				$query = "SELECT ordering AS value, name AS text"
				. "\n FROM #__comprofiler_plugin"
				. "\n WHERE type='" . $_CB_database->getEscaped( $row->type ) . "'"
				. "\n AND published > 0"
				. "\n AND ordering > -10000"
				. "\n AND ordering < 10000"
				. "\n ORDER BY ordering"
				;
				$order = $this->_cbGetOrderingList( $query );
				$lists['ordering'] = moscomprofilerHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"', 'value', 'text', intval( $row->ordering ), 2 );
			} else {
				$lists['ordering'] = '<input type="hidden" name="ordering" value="'. $row->ordering .'" />' . CBTxt::T('This plugin cannot be reordered');
			}
			$lists['type'] = '<input type="hidden" name="type" value="'. $row->type .'" />'. $row->type;
	
			if ($element && $element->name() == 'cbinstall' && $element->attributes( 'type' ) == 'plugin' ) {
				$description =& $element->getElementByPath( 'description' );
				$row->description = ( $description ) ? trim( $description->data() ) : '';
			}
	
		} else {
			$row->folder 		= '';
			$row->ordering 		= 999;
			$row->published 	= 1;
			$row->description 	= '';
	
			$folders			= cbReadDirectory( $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' );
			$folders2			= array();
			foreach ($folders as $folder) {
			    if (is_dir( $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/' . $folder ) && ( $folder <> 'CVS' ) ) {
			        $folders2[] = moscomprofilerHTML::makeOption( $folder );
				}
			}
			$lists['type']		= moscomprofilerHTML::selectList( $folders2, 'type', 'class="inputbox" size="1"', 'value', 'text', null, 2 );
			$lists['ordering']	= '<input type="hidden" name="ordering" value="'. $row->ordering .'" />' . CBTxt::T('New items default to the last place. Ordering can be changed after this item is saved.') ;
		}
	
		$Yesoptions = array();
		$Yesoptions[] = moscomprofilerHTML::makeOption( '1', _UE_YES );
		if ( ( $row->type == 'language' ) || ( $row->id == 1 ) ) {
			$row->published		=	1;
		} else {
			$Yesoptions[]		=	moscomprofilerHTML::makeOption( '0', _UE_NO );
		}
		$lists['published'] = moscomprofilerHTML::radioList( $Yesoptions, 'published', 'class="inputbox"', 'value', 'text', $row->published, 2 );
	
		$pluginView				=	_CBloadView( 'plugin' );
		$pluginView->editPlugin( $row, $lists, $params, $options );
	}
function cbInstaller_install_plugins(&$return)
{
    global $_CB_framework, $_CB_adminpath, $ueConfig;
    cbimport('cb.adminfilesystem');
    cbimport('cb.installer');
    $cbDatabase = \CBLib\Application\Application::Database();
    // List of core plugins that are no longer core, but we just want to disable core status and not remove as they don't conflict:
    $deprecated = array('bootstrap', 'winclassic', 'webfx', 'osx', 'luna', 'dark', 'yanc', 'cb.mamblogtab', 'cb.simpleboardtab', 'cb.authortab');
    foreach ($deprecated as $pluginElement) {
        $plugin = new PluginTable();
        if ($plugin->load(array('element' => $pluginElement))) {
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('iscore') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('id') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_tabs') . "\n SET " . $cbDatabase->NameQuote('sys') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('pluginid') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] tabs failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n SET " . $cbDatabase->NameQuote('sys') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('pluginid') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] fields failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
        }
    }
    // List of plugins that conflict with the core that need to be removed (normally due to being merged into core):
    $conflicted = array('bootstrap', 'winclassic', 'webfx', 'osx', 'luna', 'dark', 'yanc', 'cb.mamblogtab', 'cb.authortab', 'cbvideofield', 'cb.filefield');
    foreach ($conflicted as $pluginElement) {
        $plugin = new PluginTable();
        if ($plugin->load(array('element' => $pluginElement))) {
            if (!cbInstaller_uninstall_plugin($plugin, $return)) {
                return false;
            }
        }
    }
    // Ensure Default template, CB Core, and language plugins are published as they are not allowed to be unpublished:
    $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('published') . " = 1" . "\n WHERE ( " . $cbDatabase->NameQuote('id') . " IN " . $cbDatabase->safeArrayOfIntegers(array(1, 7)) . ' OR ' . $cbDatabase->NameQuote('type') . ' = ' . $cbDatabase->quote('language') . ' )';
    $cbDatabase->setQuery($query);
    $cbDatabase->query();
    $pluginsFile = $_CB_adminpath . 'pluginsfiles.tgz';
    // We need to ensure the core plugins archive actually exists before doing anything with it:
    if (!file_exists($pluginsFile)) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Core plugins archive [path] missing.', array('[path]' => $pluginsFile)) . '</div>';
        return false;
    }
    // We need zlib to unzip packages so lets check that it exists:
    if (!extension_loaded('zlib')) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::T('Core plugins can not be installed as zlib is not installed.') . '</div>';
        return false;
    }
    $installer = new cbInstallerPlugin();
    // Uncompress the core plugins so we can install them:
    if (!$installer->upload($pluginsFile, true, false)) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Core plugins can not be installed as uncompressing [path] failed.', array('[path]' => $pluginsFile)) . '</div>';
        return false;
    }
    $adminFS = cbAdminFileSystem::getInstance();
    $baseDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler';
    // Create the base plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin')) {
        if (!$adminFS->mkdir($baseDir . '/plugin')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/index.html')) . '</div>';
            return false;
        }
    }
    // Create the language template directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/language')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/language')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/language')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/language/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/language/index.html')) . '</div>';
            return false;
        }
    }
    // Create the template plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/templates')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/templates')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/templates')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/templates/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/templates/index.html')) . '</div>';
            return false;
        }
    }
    // Create the user plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/user')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/user')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/user')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/user/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/user/index.html')) . '</div>';
            return false;
        }
    }
    // Install core plugins 1 by 1 silently:
    $installFrom = $installer->installDir();
    $filesList = cbReadDirectory($installFrom, '.', true);
    foreach ($filesList as $file) {
        if (preg_match('/^.+\\.xml$/i', $file)) {
            $plgPath = $installFrom . (substr($installFrom, -1, 1) == '/' ? '' : '/') . $file;
            $plgXml = new SimpleXMLElement(trim(file_get_contents($plgPath)));
            if ($plgXml->getName() == 'cbinstall') {
                $plgDir = dirname($plgPath) . '/';
                ob_start();
                $plgInstaller = new cbInstallerPlugin();
                $installed = $plgInstaller->install($plgDir);
                ob_end_clean();
                if (!$installed) {
                    $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Installing core plugin [plugin] failed with error [error].', array('[plugin]' => $plgInstaller->i_elementname ? $plgInstaller->i_elementname : $file, '[error]' => $plgInstaller->getError())) . '</div>';
                    return false;
                }
            }
        }
    }
    // Delete the expanded core plugins archive:
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::T('Deleting expanded core plugins archive failed.') . '</div>';
    }
    // Delete the core plugins archive:
    $result = $adminFS->unlink(_cbPathName($pluginsFile, false));
    if ($result === false) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Deleting core plugins archive [path] failed.', array('[path]' => $pluginsFile)) . '</div>';
    }
    // Sets the as ready so config can actually load this time:
    \CB\Application\CBConfig::setCbConfigReadyToLoad(true);
    // Load the config now that the tables exist encase they didn't during install:
    \CB\Application\CBConfig::loadLegacyCBueConfig();
    // Migrate old file based configuration to database based configuration:
    $newConfig = null;
    if ($adminFS->file_exists($_CB_adminpath . 'ue_config.php')) {
        /** @noinspection PhpIncludeInspection */
        include_once $_CB_adminpath . 'ue_config.php';
        // Reset the template back to default if upgrading from a 1.x install:
        $ueConfig['templatedir'] = 'default';
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x nesttabs into new nested tab display mode if needed:
    if (isset($ueConfig['nesttabs'])) {
        // Update all the tabs that would have normally auto-nested and make them nested displays
        $query = 'UPDATE ' . $cbDatabase->NameQuote('#__comprofiler_tabs') . "\n SET " . $cbDatabase->NameQuote('displaytype') . " = " . $cbDatabase->Quote('nested') . "\n WHERE " . $cbDatabase->NameQuote('displaytype') . " = " . $cbDatabase->Quote('tab') . "\n AND " . $cbDatabase->NameQuote('fields') . " = 1" . "\n AND ( ( " . $cbDatabase->NameQuote('pluginclass') . " IS NULL )" . ' OR ( ' . $cbDatabase->NameQuote('sys') . ' = 2 ) )';
        $cbDatabase->setQuery($query);
        $cbDatabase->query();
        unset($ueConfig['nesttabs']);
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global avatar params to field params:
    if (isset($ueConfig['allowAvatar']) || isset($ueConfig['defaultAvatar']) || isset($ueConfig['defaultPendingAvatar']) || isset($ueConfig['allowAvatarGallery'])) {
        $field = new FieldTable();
        if ($field->load(array('name' => 'avatar'))) {
            $fieldParams = new Registry($field->params);
            if (isset($ueConfig['allowAvatar'])) {
                $fieldParams->set('image_allow_uploads', (int) $ueConfig['allowAvatar']);
                unset($ueConfig['allowAvatar']);
            }
            if (isset($ueConfig['defaultAvatar'])) {
                $fieldParams->set('defaultAvatar', $ueConfig['defaultAvatar']);
                unset($ueConfig['defaultAvatar']);
            }
            if (isset($ueConfig['defaultPendingAvatar'])) {
                $fieldParams->set('defaultPendingAvatar', $ueConfig['defaultPendingAvatar']);
                unset($ueConfig['defaultPendingAvatar']);
            }
            if (isset($ueConfig['allowAvatarGallery'])) {
                $fieldParams->set('image_allow_gallery', (int) $ueConfig['allowAvatarGallery']);
                unset($ueConfig['allowAvatarGallery']);
            }
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global email ajax checker to field specific param:
    if (isset($ueConfig['reg_email_checker'])) {
        $field = new FieldTable();
        if ($field->load(array('name' => 'email'))) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('field_check_email', (string) $ueConfig['reg_email_checker']);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        unset($ueConfig['reg_email_checker']);
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global image params to field params:
    if (isset($ueConfig['allowAvatarUpload'])) {
        $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('name') . " != " . $cbDatabase->Quote('avatar') . "\n AND " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('image');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('image_allow_uploads', (int) $ueConfig['allowAvatarUpload']);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        unset($ueConfig['allowAvatarUpload']);
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x allow_profileviewbyGID into new profile_viewaccesslevel if needed:
    if (isset($ueConfig['allow_profileviewbyGID']) && !isset($ueConfig['profile_viewaccesslevel'])) {
        $ueConfig['profile_viewaccesslevel'] = \CBLib\Application\Application::CmsPermissions()->convertOldGroupToViewAccessLevel($ueConfig['allow_profileviewbyGID'], 'CB Profiles access');
        unset($ueConfig['allow_profileviewbyGID']);
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x allow_profileviewbyGID into new profile_viewaccesslevel if needed:
    if (isset($ueConfig['imageApproverGid']) && !isset($ueConfig['moderator_viewaccesslevel'])) {
        $ueConfig['moderator_viewaccesslevel'] = \CBLib\Application\Application::CmsPermissions()->convertOldGroupToViewAccessLevel($ueConfig['imageApproverGid'], 'CB Moderators access');
        unset($ueConfig['imageApproverGid']);
        $newConfig = json_encode($ueConfig);
    }
    // If old configuration for terms and conditions exists we need to pass it to the terms and conditions field:
    if (isset($ueConfig['reg_enable_toc']) && isset($ueConfig['reg_toc_url'])) {
        if ($ueConfig['reg_enable_toc'] == 1 && $ueConfig['reg_toc_url'] != '') {
            $field = new FieldTable();
            if ($field->load(array('name' => 'acceptedterms'))) {
                $fieldParams = new Registry($field->params);
                if ($fieldParams->get('terms_url') == '') {
                    $fieldParams->set('terms_url', $ueConfig['reg_toc_url']);
                    $field->set('required', 1);
                    $field->set('registration', 1);
                    $field->set('edit', 1);
                    $field->set('params', $fieldParams->asJson());
                    if (!$field->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
                    }
                }
            }
        }
        unset($ueConfig['reg_enable_toc']);
        unset($ueConfig['reg_toc_url']);
        $newConfig = json_encode($ueConfig);
    }
    // If old configuration for userlists exists we need to pass it to the userlist it self:
    if (isset($ueConfig['num_per_page']) && isset($ueConfig['allow_profilelink'])) {
        if ($ueConfig['num_per_page'] != '' || $ueConfig['allow_profilelink'] != 1) {
            $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_lists');
            $cbDatabase->setQuery($query);
            $lists = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($cbDatabase));
            /** @var $lists ListTable[] */
            foreach ($lists as $list) {
                $listParams = new Registry($list->params);
                $changed = false;
                if ($ueConfig['num_per_page'] != '' && $listParams->get('list_limit') == '') {
                    $listParams->set('list_limit', $ueConfig['num_per_page']);
                    $changed = true;
                }
                if ($ueConfig['allow_profilelink'] != 1 && $listParams->get('allow_profilelink') == '') {
                    $listParams->set('allow_profilelink', $ueConfig['allow_profilelink']);
                    $changed = true;
                }
                if ($changed) {
                    $list->set('params', $listParams->asJson());
                    if (!$list->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Userlist [title] failed to migrate. Error: [error]', array('[name]' => $list->title, '[error]' => $list->getError())) . '</div>';
                    }
                }
            }
        }
        unset($ueConfig['num_per_page']);
        unset($ueConfig['allow_profilelink']);
        $newConfig = json_encode($ueConfig);
    }
    // Establish default for any missing config params:
    $configXml = new SimpleXMLElement(trim(file_get_contents($_CB_adminpath . 'xmlcb/views/view.com_comprofiler.editconfig.xml')));
    if ($configXml) {
        $configXmlParams = $configXml->xpath('//param');
        if ($configXmlParams) {
            $configXmlSet = false;
            foreach ($configXmlParams as $configXmlParam) {
                $k = (string) $configXmlParam->attributes('name');
                if (!isset($ueConfig[$k])) {
                    $v = (string) $configXmlParam->attributes('default');
                    if ($k) {
                        $ueConfig[$k] = $v;
                        $configXmlSet = true;
                    }
                }
            }
            if ($configXmlSet) {
                $newConfig = json_encode($ueConfig);
            }
        }
    }
    // Update cb.core with the new cb config:
    if ($newConfig) {
        $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('params') . " = " . $cbDatabase->Quote($newConfig) . "\n WHERE " . $cbDatabase->NameQuote('id') . " = 1";
        $cbDatabase->setQuery($query);
        if (!$cbDatabase->query()) {
            $_CB_framework->enqueueMessage(CBTxt::P('Failed to update configuration params in database. Error: [error]', array('[error]' => $cbDatabase->getErrorMsg())), 'error');
            return false;
        }
    }
    // Remove the old config file if it exists as we migrated above already:
    if ($adminFS->file_exists($_CB_adminpath . 'ue_config.php')) {
        $adminFS->unlink($_CB_adminpath . 'ue_config.php');
    }
    // Migrate old userlist columns to new usage:
    $tableFields = $cbDatabase->getTableFields('#__comprofiler_lists');
    if (isset($tableFields['#__comprofiler_lists'])) {
        $userListFields = array_keys($tableFields['#__comprofiler_lists']);
        $userListOldFields = array('useraccessgroupid', 'sortfields', 'filterfields', 'col1title', 'col1enabled', 'col1fields', 'col1captions', 'col2title', 'col2enabled', 'col2fields', 'col2captions', 'col3title', 'col3enabled', 'col3fields', 'col3captions', 'col4title', 'col4enabled', 'col4fields', 'col4captions');
        // At least 1 legacy column still exists so lets begin migration of userlists:
        if (array_intersect($userListOldFields, $userListFields)) {
            $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_lists');
            $cbDatabase->setQuery($query);
            $lists = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($cbDatabase));
            /** @var $lists ListTable[] */
            foreach ($lists as $list) {
                $listParams = new Registry($list->params);
                $listSorting = array();
                $listSortFields = $list->get('sortfields') ? explode(', ', str_replace('`', '', $list->get('sortfields'))) : array();
                $paramsChanged = false;
                foreach ($listSortFields as $listSortField) {
                    $sortParts = explode(' ', $listSortField);
                    $sortField = isset($sortParts[0]) ? trim($sortParts[0]) : null;
                    if ($sortField) {
                        $sortDirection = isset($sortParts[1]) ? trim($sortParts[1]) : 'ASC';
                        $listSorting[] = array('column' => $sortField, 'direction' => $sortDirection);
                    }
                }
                if ($listSorting) {
                    $paramsChanged = true;
                    $listParams->set('sort_mode', '0');
                    $listParams->set('basic_sort', $listSorting);
                }
                $listFilterFields = $list->get('filterfields');
                if ($listFilterFields) {
                    $filterType = substr($listFilterFields, 0, 1);
                    $listFilterFields = rawurldecode(substr($listFilterFields, 2, -1));
                    if ($filterType == 'a') {
                        $paramsChanged = true;
                        $listParams->set('filter_mode', '1');
                        $listParams->set('filter_advanced', $listFilterFields);
                    } else {
                        $listFilters = array();
                        $basicFilters = explode(' AND ', $listFilterFields);
                        foreach ($basicFilters as $basicFilter) {
                            if (preg_match('/`(.+)`\\s*(.+)\\s*\'(.*)\'|`(.+)`\\s*(.+)/i', $basicFilter, $matches)) {
                                $filterField = isset($filterParts[1]) ? $filterParts[1] : (isset($filterParts[4]) ? $filterParts[4] : null);
                                $filterOperator = isset($filterParts[2]) ? $filterParts[2] : (isset($filterParts[5]) ? $filterParts[5] : null);
                                $filterVal = isset($filterParts[3]) ? $filterParts[3] : '';
                                switch ($filterOperator) {
                                    case '!=':
                                        $filterOperator = '<>||ISNULL';
                                        break;
                                    case 'IS NULL':
                                    case "= ''":
                                        $filterOperator = '=';
                                        $filterVal = '';
                                        break;
                                    case 'IS NOT NULL':
                                    case "!= ''":
                                        $filterOperator = '!=';
                                        $filterVal = '';
                                        break;
                                }
                                if ($filterField && $filterOperator) {
                                    $listFilters[] = array('column' => $filterField, 'operator' => $filterOperator, 'value' => $filterVal);
                                }
                            }
                        }
                        if ($listFilters) {
                            $paramsChanged = true;
                            $listParams->set('filter_mode', '0');
                            $listParams->set('filter_basic', $listFilters);
                        }
                    }
                }
                $listColumns = array();
                for ($i = 1, $n = 4; $i <= $n; $i++) {
                    if ($list->get('col' . $i . 'enabled')) {
                        $columnTitle = $list->get('col' . $i . 'title', '');
                        $columnCaptions = (int) $list->get('col' . $i . 'captions', 0);
                        $columnFields = $list->get('col' . $i . 'fields') ? explode('|*|', $list->get('col' . $i . 'fields')) : array();
                        $listFields = array();
                        foreach ($columnFields as $columnField) {
                            $listFields[] = array('field' => (string) $columnField, 'display' => $columnCaptions ? '1' : '4');
                        }
                        if ($listFields) {
                            $listColumns[] = array('title' => $columnTitle, 'size' => '3', 'cssclass' => '', 'fields' => $listFields);
                        }
                    }
                }
                if ($listColumns) {
                    $paramsChanged = true;
                    $listParams->set('columns', $listColumns);
                }
                if ($paramsChanged || $list->get('usergroupids')) {
                    $list->set('usergroupids', implode('|*|', explode(', ', $list->get('usergroupids'))));
                    $list->set('params', $listParams->asJson());
                    if (!$list->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Userlist [title] failed to migrate. Error: [error]', array('[name]' => $list->title, '[error]' => $list->getError())) . '</div>';
                    }
                }
            }
            $userListDrop = array();
            foreach ($userListOldFields as $userListOldField) {
                if (in_array($userListOldField, $userListFields)) {
                    $userListDrop[] = $cbDatabase->NameQuote($userListOldField);
                }
            }
            if ($userListDrop) {
                $query = 'ALTER TABLE ' . $cbDatabase->NameQuote('#__comprofiler_lists') . "\n DROP " . implode(', DROP ', $userListDrop);
                $cbDatabase->setQuery($query);
                $cbDatabase->query();
            }
        }
    }
    // Migrates password strength parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbpasswordstrength'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('password');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('passTestSrength', (string) $fieldParams->get('pswstr_display', 1));
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates ajax points field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbajaxpointsfield'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('ajaxpoints');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            switch ((int) $fieldParams->get('ajax_layout', 1)) {
                case 1:
                    $fieldParams->set('points_layout', '[minus] [value] [plus]');
                    break;
                case 2:
                    $fieldParams->set('points_layout', '[plus] [value] [minus]');
                    break;
                case 3:
                    $fieldParams->set('points_layout', '[value] [minus][plus]');
                    break;
                case 4:
                    $fieldParams->set('points_layout', '[value] [plus][minus]');
                    break;
                case 5:
                    $fieldParams->set('points_layout', '[minus][plus] [value]');
                    break;
                case 6:
                    $fieldParams->set('points_layout', '[plus][minus] [value]');
                    break;
            }
            $fieldParams->set('points_inc_plus', (string) $fieldParams->get('ajax_increment_up', 1));
            $fieldParams->set('points_inc_minus', (string) $fieldParams->get('ajax_increment_down', 1));
            $fieldParams->set('points_access', '8');
            $fieldParams->set('points_access_custom', (string) $fieldParams->get('ajax_access', 0));
            $field->set('type', 'points');
            $field->set('pluginid', 1);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates rating field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'ratingfield'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " IN " . $cbDatabase->safeArrayOfStrings(array('myrating', 'yourrating'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            if ($field->type == 'myrating') {
                $fieldParams->set('rating_access', '2');
            } else {
                if ($fieldParams->get('AllowAnnonymous', 1)) {
                    $fieldParams->set('rating_access', '3');
                } else {
                    $fieldParams->set('rating_access', '4');
                    $fieldParams->set('rating_access_exclude', '1');
                }
            }
            $fieldParams->set('rating_number', (string) $fieldParams->get('NumStars', 5));
            switch ((int) $fieldParams->get('RatingFraction', 1)) {
                case 1:
                    $fieldParams->set('rating_step', '1');
                    break;
                case 2:
                    $fieldParams->set('rating_step', '0.5');
                    break;
                case 3:
                    $fieldParams->set('rating_step', '0.33');
                    break;
                case 4:
                    $fieldParams->set('rating_step', '0.25');
                    break;
            }
            $field->set('type', 'rating');
            $field->set('pluginid', 1);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates verify email field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbverifyemail'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " IN " . $cbDatabase->safeArrayOfStrings(array('emailaddress', 'primaryemailaddress'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('fieldVerifyInput', $fieldParams->get('verifyemail_display_reg', 1) || $fieldParams->get('verifyemail_display_edit', 0) ? '1' : '0');
            $fieldParams->set('verifyEmailTitle', $fieldParams->get('verifyemail_title', '_UE_VERIFY_SOMETHING'));
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates forum integration parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cb.simpleboardtab'))) {
        $pluginParams = new Registry($plugin->params);
        $cbForums = new PluginTable();
        if ($cbForums->load(array('element' => 'cbforums'))) {
            $cbForumsParams = new Registry($cbForums->params);
            if ((int) $pluginParams->get('forumType', 0) == 4) {
                $cbForumsParams->set('forum_model', '6');
            } else {
                $cbForumsParams->set('forum_model', '1');
            }
            switch ((int) $pluginParams->get('sidebarMode', 0)) {
                case 1:
                    $cbForumsParams->set('k20_personaltext', $pluginParams->get('sidebarBeginner1'));
                    $cbForumsParams->set('k20_gender', $pluginParams->get('sidebarBeginner4'));
                    $cbForumsParams->set('k20_birthdate', $pluginParams->get('sidebarBeginner2'));
                    $cbForumsParams->set('k20_location', $pluginParams->get('sidebarBeginner3'));
                    $cbForumsParams->set('k20_icq', $pluginParams->get('sidebarBeginner5'));
                    $cbForumsParams->set('k20_aim', $pluginParams->get('sidebarBeginner6'));
                    $cbForumsParams->set('k20_yim', $pluginParams->get('sidebarBeginner7'));
                    $cbForumsParams->set('k20_msn', $pluginParams->get('sidebarBeginner8'));
                    $cbForumsParams->set('k20_skype', $pluginParams->get('sidebarBeginner9'));
                    $cbForumsParams->set('k20_twitter', $pluginParams->get('sidebarBeginner12'));
                    $cbForumsParams->set('k20_facebook', $pluginParams->get('sidebarBeginner13'));
                    $cbForumsParams->set('k20_gtalk', $pluginParams->get('sidebarBeginner10'));
                    $cbForumsParams->set('k20_myspace', $pluginParams->get('sidebarBeginner14'));
                    $cbForumsParams->set('k20_linkedin', $pluginParams->get('sidebarBeginner15'));
                    $cbForumsParams->set('k20_delicious', $pluginParams->get('sidebarBeginner16'));
                    $cbForumsParams->set('k20_digg', $pluginParams->get('sidebarBeginner18'));
                    $cbForumsParams->set('k20_blogspot', $pluginParams->get('sidebarBeginner19'));
                    $cbForumsParams->set('k20_flickr', $pluginParams->get('sidebarBeginner20'));
                    $cbForumsParams->set('k20_bebo', $pluginParams->get('sidebarBeginner21'));
                    $cbForumsParams->set('k20_website', $pluginParams->get('sidebarBeginner11'));
                    break;
                case 2:
                    $cbForumsParams->set('k20_sidebar_reg', $pluginParams->get('sidebarAdvancedExists'));
                    $cbForumsParams->set('k20_sidebar_anon', $pluginParams->get('sidebarAdvancedPublic'));
                    $cbForumsParams->set('k20_sidebar_del', $pluginParams->get('sidebarAdvancedDeleted'));
                    break;
            }
            $cbForums->set('params', $cbForumsParams->asJson());
            if (!$cbForums->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] failed to migrate. Error: [error]', array('[element]' => $plugin->element, '[error]' => $cbForums->getError())) . '</div>';
            }
        }
        // Migrate the forum fields to ensure their display mode is set:
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('name') . " IN " . $cbDatabase->safeArrayOfStrings(array('forumrank', 'forumposts', 'forumkarma'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            switch ($field->name) {
                case 'forumposts':
                    $fieldParams->set('forumStatus', 'posts');
                    break;
                case 'forumkarma':
                    $fieldParams->set('forumStatus', 'karma');
                    break;
                case 'forumrank':
                    $fieldParams->set('forumStatus', 'rank');
                    break;
            }
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Removes legacy about cb menu items from CB Menu tab params
    $tab = new TabTable();
    if ($tab->load(17)) {
        $tabParams = new Registry($tab->params);
        if ($tabParams->get('firstSubMenuName') == '_UE_MENU_ABOUT_CB') {
            $tabParams->set('firstSubMenuName', '');
            $tabParams->set('firstSubMenuHref', '');
            if ($tabParams->get('firstMenuName') == '_UE_MENU_CB' && !$tabParams->get('secondSubMenuName')) {
                $tabParams->set('firstMenuName', '');
            }
            $tab->set('params', $tabParams->asJson());
            if (!$tab->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Tab [title] failed to migrate. Error: [error]', array('[title]' => $tab->title, '[error]' => $tab->getError())) . '</div>';
            }
        }
    }
    // We need to fix the name fields publish state:
    switch ($ueConfig['name_style']) {
        case 2:
            $nameArray = array('name' => 0, 'firstname' => 1, 'middlename' => 0, 'lastname' => 1);
            break;
        case 3:
            $nameArray = array('name' => 0, 'firstname' => 1, 'middlename' => 1, 'lastname' => 1);
            break;
        case 1:
        default:
            $nameArray = array('name' => 1, 'firstname' => 0, 'middlename' => 0, 'lastname' => 0);
            break;
    }
    foreach ($nameArray as $name => $published) {
        $query = 'UPDATE ' . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n SET " . $cbDatabase->NameQuote('published') . " = " . (int) $published . "\n WHERE " . $cbDatabase->NameQuote('name') . " = " . $cbDatabase->Quote($name);
        $cbDatabase->setQuery($query);
        $cbDatabase->query();
    }
    return true;
}
 /**
  * Tries to find the package XML file
  *
  * @return boolean  True on success, False on error
  */
 function findInstallFile()
 {
     $found = false;
     // Search the install dir for an xml file
     $files = cbReadDirectory($this->installDir(), '.xml$', true, false);
     if (count($files) == 0) {
         $this->setError(1, 'ERROR: Could not find an XML setup file in the package.');
         return false;
     }
     foreach ($files as $file) {
         $packagefile = $this->isPackageFile($this->installDir() . $file);
         if (!is_null($packagefile) && !$found) {
             $this->i_xmldocument = $packagefile;
             return true;
         }
     }
     $this->setError(1, 'ERROR: Could not find a CB XML setup file in the package.');
     return false;
 }