diff --git a/lib/CBFUtility.php b/lib/CBFUtility.php deleted file mode 100755 index d69bf180a..000000000 --- a/lib/CBFUtility.php +++ /dev/null @@ -1,715 +0,0 @@ -getSiteID(); - $this->_db = DatabaseConnection::getInstance(); - $this->_structure = array(); - $this->_keys = array(); - $this->_siteID = $siteID; - $this->_GUID = 0; - $this->_GUIDs = array(); - $this->_GUIDRestores = array(); - $this->_dataOverwrite = $dataOverwrite; - } - - public function into() - { - //$this->deleteSiteData(); - $this->doCreateBackup('TMP'); - $this->doRestoreBackup('TMP'); - } - - // FIXME: Document me. - public function doBuildStructure() - { - $tables = preg_split('/[\,\;\-\t ]+/', CBF_TABLES); - foreach ($tables as $tableName) - { - $this->doScanTable(strtolower($tableName)); - } - } - - // FIXME: Document me. - public function doBuildAssociations() - { - foreach ($this->_structure as $tableName => $tableData) - { - foreach ($tableData as $fieldName => $fieldData) - { - if ($fieldData['PRI']) - { - continue; - } - - foreach ($this->_keys as $keyFieldName => $keyTableName) - { - if (!strcmp($keyFieldName, $fieldName)) - { - $this->_structure[$tableName][$fieldName]['foreign'] = $keyTableName; - } - } - } - } - } - - public function doScanTable($tableName) - { - $hasSiteID = false; - $tableStructure = array(); - - $sql = sprintf( - "SHOW COLUMNS - FROM - %s", - $tableName - ); - - $rs = $this->_db->getAllAssoc($sql); - if (empty($rs)) - { - return false; - } - - foreach ($rs as $row) - { - $tableStructure[$row['Field']] = array( - 'Type' => $row['Type'], - 'PRI' => ($row['Key'] == 'PRI') ? true : false, - 'Null' => ($row['Null'] == 'NO') ? false : true - ); - - if ($row['Key'] == 'PRI') - { - $primaryKey = $row['Field']; - } - - // Prevent tables with no site_id from being backed up - if (!strcmp($row['Field'], 'site_id')) - { - $hasSiteID = true; - } - } - - if ($hasSiteID) - { - $this->_structure[$tableName] = $tableStructure; - $this->_keys[$primaryKey] = $tableName; - } - - return true; - } - - // FIXME: Document me. - public function getForeignKeys($tableData) - { - $result = array(); - foreach ($tableData as $fieldName => $fieldData) - { - if (isset($fieldData[$id = 'foreign'])) - { - $result[] = $fieldData[$id]; - } - } - return $result; - } - - // FIXME: Document me. - public function getTablesByForeignKeys($allowedKeys) - { - $result = array(); - foreach ($this->_structure as $tableName => $tableData) - { - $foreignKeys = $this->getForeignKeys($tableData); - if (count($foreignKeys) == $allowedKeys) - { - $result[$tableName] = $tableData; - } - } - - return $result; - } - - // FIXME: Document me. - private function isTableSiteRestricted($tableData) - { - foreach ($tableData as $fieldName => $fieldData) - { - if (!strcmp($fieldName, 'site_id')) - { - return true; - } - } - - return false; - } - - // FIXME: Document me. - private function setGUID($fieldName, $id) - { - $id = intval($id); - if (!$this->_GUIDSwapEnabled) - { - if (!isset($this->_GUIDs[$fieldName])) - { - return ($this->_GUIDs[$fieldName] = array( $id => ($this->_GUID++) )); - } - - else if (isset($this->_GUIDs[$fieldName][$id])) - { - // already exists - return $this->_GUIDs[$fieldName][$id]; - } - - else return ($this->_GUIDs[$fieldName][$id] = ($this->_GUID++)); - } - - /* If $this->_GUIDSwapEnabled is set to true, the GUIDs are stored in - * a swap file and not in memory. - */ - fseek($this->_GUIDSwap, 0, SEEK_END); - fwrite($this->_GUIDSwap, sprintf('%30s', $fieldName), 30); - fwrite($this->_GUIDSwap, pack('N1', $id)); - fwrite($this->_GUIDSwap, pack('N1', $this->_GUID)); - - return $this->_GUID++; - } - - // FIXME: Document me. - private function getGUID($fieldName, $id) - { - $id = intval($id); - if (!$this->_GUIDSwapEnabled) - { - if (!isset($this->_GUIDs[$fieldName]) || !isset($this->_GUIDs[$fieldName][$id])) - { - // Record points to a non-existent row - return false; - } - return $this->_GUIDs[$fieldName][$id]; - } - - /* If $this->_GUIDSwapEnabled is set to true, the GUIDs are stored in - * a swap file and not in memory. - */ - rewind($this->_GUIDSwap); - for ($guidIndex = 0; $guidIndex < $this->_GUID; $guidIndex++) - { - $rName = fread($this->_GUIDSwap, 30); - $rIdBin = fread($this->_GUIDSwap, 4); - $rGUIDBin = fread($this->_GUIDSwap, 4); - - /* Decode binary data. */ - $rId = array_pop(unpack('N1', $rIdBin)); - $rGUID = array_pop(unpack('N1', $rGUIDBin)); - - if (!strcasecmp($rName, $fieldName) && $id == $rId) - { - return $rGUID; - } - } - - return false; - } - - // FIXME: Document me. - private function doBuildGUIDs() - { - foreach ($this->_structure as $tableName => $tableData) - { - foreach ($tableData as $fieldName => $fieldData) - { - if (!$fieldData['PRI']) - { - continue; - } - - if ($this->isTableSiteRestricted($tableData)) - { - $siteRestrictedCriterion = sprintf( - "WHERE - %s.site_id = %s", - $tableName, - $this->_db->makeQueryInteger($this->_siteID) - ); - } - else - { - $siteRestrictedCriterion = ''; - } - - $sql = sprintf( - "SELECT - %s - FROM - %s - %s", - $fieldName, - $tableName, - $siteRestrictedCriterion - ); - - if ($rs = $this->_db->query($sql)) - { - while (($row = $this->_db->getAssoc())) - { - $this->setGUID($fieldName, $row[$fieldName]); - } - } - } - } - } - - private function getFieldType($type) - { - if (strpos(strtolower($type), 'int') !== false) return 'N'; - else if (strpos(strtolower($type), 'float') !== false) return 'N'; - else return 'S'; - } - - private function getTableInfoBackup($tableName, $tableData) - { - $info = sprintf('%s,', $tableName); - $rowCnt = 0; - foreach ($tableData as $fieldName => $fieldData) - { - if (($rowCnt++) > 0) $info .= ','; - $info .= sprintf('%s', $fieldName); - } - return $info; - } - - private function restoreTableInfoBackup($tableData) - { - $mp = explode(',', $tableData); - $tableName = $mp[0]; - $tableFields = array_slice($mp, 1); - - // Check if table exists in current schema - if (!isset($this->_structure[$tableName])) return false; - - $tableStructure = array(); - foreach ($tableFields as $newFieldName) - { - $exists = false; - foreach ($this->_structure[$tableName] as $fieldName => $fieldData) - { - if (!strcasecmp($newFieldName, $fieldName)) - { - $exists = true; - } - } - - $tableStructure[] = array('name' => $newFieldName, 'exists' => $exists); - } - - return array($tableName, $tableStructure); - } - - // FIXME: Document me. - private function getTableDataBackup($tableName, $tableData) - { - $foreignKeys = $this->getForeignKeys($tableData); - $data = false; - - if ($this->isTableSiteRestricted($tableData)) - { - $siteRestrictedCriterion = sprintf( - "WHERE - %s.site_id = %s", - $tableName, - $this->_db->makeQueryString($this->_siteID) - ); - } - else - { - $siteRestrictedCriterion = ''; - } - - $sql = sprintf( - "SELECT - * - FROM - %s - %s", - $tableName, - $siteRestrictedCriterion - ); - - if ($rs = $this->_db->query($sql)) - { - $data = pack('N1', $this->_db->getNumRows()); - - while ($row = $this->_db->getAssoc()) - { - foreach ($row as $columnField => $columnData) - { - if ($tableData[$columnField]['PRI'] || isset($tableData[$columnField]['foreign'])) - { - if (($guid = $this->getGUID($columnField, $columnData)) === false) - { - // id points to a row that doesn't exist, maintain invalidity - $data .= pack('C1', ord('D')); - $data .= pack('C1', ord($this->getFieldType($tableData[$columnField]['Type']))); - $data .= pack('N1', strlen($columnData)); - $data .= $columnData; - } - else - { - $data .= pack('C1', ord('G')); - $data .= pack('N1', $guid); - } - } - else - { - $data .= pack('C1', ord('D')); - $data .= pack('C1', ord($this->getFieldType($tableData[$columnField]['Type']))); - $data .= pack('N1', strlen($columnData)); - $data .= $columnData; - } - } - } - } - - return $data; - } - - private function restoreTableDataBackup($tableName, $tableStructure, $tableData) - { - $numFields = count($tableStructure); - $numRows = array_pop(unpack('N1', substr($tableData, 0, $size = 4))); - $tableData = substr($tableData, $size); - - $sqlInserts = array(); - - for ($rowIndex=0; $rowIndex < $numRows; $rowIndex++) - { - $sqlPre = ''; - $sqlValues = array(); - $primaryGUID = false; - - for ($fieldIndex=0; $fieldIndex < $numFields; $fieldIndex++) - { - $fieldName = $tableStructure[$fieldIndex]['name']; - - $recordType = chr(array_pop(unpack('C1', substr($tableData, 0, $size = 1)))); - $tableData = substr($tableData, $size); - $GUID = false; - - if ($recordType == 'G') - { - $GUID = array_pop(unpack('N1', substr($tableData, 0, $size = 4))); - $data = sprintf('GUID{%d}', $GUID); - $tableData = substr($tableData, $size); - $dataType = 'N'; - - if (!strcmp($fieldName, 'site_id')) - { - // replace occurances of site_id with the current site_id - $dataType = 'N'; - $data = $this->_siteID; - $this->setRestoreGUID($GUID, $this->_siteID); - } - } - else if ($recordType == 'D') - { - $dataType = chr(array_pop(unpack('C1', substr($tableData, 0, $size = 1)))); - $tableData = substr($tableData, $size); - - $dataSize = array_pop(unpack('N1', substr($tableData, 0, $size = 4))); - $tableData = substr($tableData, $size); - - $data = substr($tableData, 0, $dataSize); - $tableData = substr($tableData, $dataSize); - } - - if ($dataType == 'S') - { - $data = $this->_db->makeQueryString($data); - } - else - { - if (!strlen($data)) - { - $data = 'NULL'; - } - // Prevent sql injection - $data = addslashes($data); - } - - if ($tableStructure[$fieldIndex]['exists']) - { - if ($this->_structure[$tableName][$fieldName]['PRI']) - { - $primaryGUID = $GUID; - } - else - { - $sqlValues[$fieldName] = $data; - } - } - } - - // Do not insert site records - if (strcasecmp($tableName, 'site')) - { - // build the insertion query - $sql = sprintf( - 'INSERT INTO %s (%s) VALUES (%s)', - $tableName, // table name verified against current schema (no injection) - implode(', ', array_keys($sqlValues)), - implode(', ', array_values($sqlValues)) - ); - - // If there are no untranslated GUIDs, insert the query - $sqlInserts[] = array('GUID' => $primaryGUID, 'SQL' => $sql); - } - } - - return $sqlInserts; - } - - private function setRestoreGUID($GUID, $id) - { - // FIXME: add swap - $this->_GUIDRestores[intval($GUID)] = $id; - } - - private function getRestoreGUID($GUID) - { - if (isset($this->_GUIDRestores[intval($GUID)])) return $this->_GUIDRestores[intval($GUID)]; - else return false; - } - - public function doCreateBackup($fileName) - { - @ini_set('memory_limit', '256M'); - - /* Create a swap file for GUIDs if necessary. */ - if (CBF_GUID_SWAP_ENABLED) - { - // FIXME: tmpfile() might fail under Windows. Look at FileUtility temp file code. - if (($this->_GUIDSwap = tmpfile()) === false) - { - $this->_GUIDSwapEnabled = false; - } - else - { - $this->_GUIDSwapEnabled = true; - } - } - - $fp = fopen($fileName, 'w'); - fwrite($fp, pack('C1', ord(CBF_HANDSHAKE)), 1); - fwrite($fp, pack('N1', CBF_VERSION), 4); - - $this->doBuildStructure(); - $this->doBuildAssociations(); - $this->doBuildGUIDs(); - - /* Up to 10 foreign keys per table maximum. */ - // FIXME: Why? - for ($keys = 0; $keys < 10; $keys++) - { - $tables = $this->getTablesByForeignKeys($keys); - if (empty($tables)) - { - continue; - } - - foreach ($tables as $tableName => $tableData) - { - $info = $this->getTableInfoBackup($tableName, $tableData); - fwrite($fp, pack('N1', strlen($info)), 4); - fwrite($fp, $info); - - $data = $this->getTableDataBackup($tableName, $tableData); - fwrite($fp, pack('N1', strlen($data)), 4); - fwrite($fp, $data); - } - } - - if ($this->_GUIDSwapEnabled) - { - fclose($this->_GUIDSwap); - } - - fclose($fp); - } - - public function deleteSiteData() - { - if (!count($this->_structure)) - { - $this->doBuildStructure(); - $this->doBuildAssociations(); - } - - // Remove all existing site data - foreach ($this->_structure as $tableName => $tableData) - { - // Maintain the existing site table - if (!strcmp($tableName, 'site')) continue; - - $sql = sprintf( - "DELETE FROM - %s - WHERE - %s.site_id = %s", - $tableName, - $tableName, - $this->_db->makeQueryString($this->_siteID) - ); - - $this->_db->query($sql); - } - - return true; - } - - public function doRestoreBackup($fileName) - { - $restoredRows = 0; - - $fileSize = filesize($fileName); - $fp = fopen($fileName, 'r'); - $handshake = chr(array_pop(unpack('C1', fread($fp, 1)))); - $version = array_pop(unpack('N1', fread($fp, 4))); - - if (strcmp($handshake, CBF_HANDSHAKE) || $version != CBF_VERSION) - { - return false; - } - - $this->doBuildStructure(); - $this->doBuildAssociations(); - - if ($this->_dataOverwrite) - { - $this->deleteSiteData(); - } - - $sqlInserts = array(); - - while (!feof($fp) && ftell($fp) != $fileSize) - { - // Get info for the first table - $tableInfoSize = array_pop(unpack('N1', fread($fp, 4))); - $data = fread($fp, $tableInfoSize); - list($tableName, $tableStructure) = $this->restoreTableInfoBackup($data); - - $tableDataSize = array_pop(unpack('N1', fread($fp, 4))); - $data = fread($fp, $tableDataSize); - $sqlInserts = array_merge($sqlInserts, - $this->restoreTableDataBackup($tableName, $tableStructure, $data) - ); - } - - while (count($sqlInserts) > 0) - { - $tmp = array(); - for ($sqlIndex=0; $sqlIndex < count($sqlInserts); $sqlIndex++) - { - $sqlInsert = $sqlInserts[$sqlIndex]; - if (strpos($sqlInsert['SQL'], 'GUID{') === false) - { - $this->_db->query($sqlInsert['SQL']); - { - $this->setRestoreGUID($sqlInsert['GUID'], $id = $this->_db->getLastInsertID()); - $searchString = sprintf('GUID{%d}', $sqlInsert['GUID']); - $replaceString = $id; - - // Replace remaining links to the new GUID - for ($sqlIndex2 = $sqlIndex + 1; $sqlIndex2 < count($sqlInserts); $sqlIndex2++) - { - $sqlInserts[$sqlIndex2]['SQL'] = - str_replace( - $searchString, - $replaceString, - $sqlInserts[$sqlIndex2]['SQL'] - ); - } - - // Replace links to the GUID we've already tried to process for the next pass - for ($sqlIndex2 = 0; $sqlIndex2 < count($tmp); $sqlIndex2++) - { - $tmp[$sqlIndex2]['SQL'] = - str_replace( - $searchString, - $replaceString, - $sqlInserts[$sqlIndex2]['SQL'] - ); - } - } - } - else - { - $tmp[] = $sqlInsert; - } - } - if (count($tmp) == count($sqlInserts)) - { - // no work was done, can't continue, prevent infinate loop - break; - } - else - { - $sqlInserts = $tmp; - } - } - - if (count($sqlInserts) > 0) - { - echo "









"; - htmlentities(print_r($sqlInserts)); - echo count($sqlInserts) . ' rows were unable to be inserted.'; - - - foreach ($sqlInserts as $mp) - { - echo "Unable to translate " . substr($mp['SQL'], strpos($mp['SQL'], 'GUID{'), 10) . "...
\n"; - } - } - - fclose($fp); - - return $restoredRows; - } -} - -?> diff --git a/lib/ControlPanel.php b/lib/ControlPanel.php deleted file mode 100755 index ade739b30..000000000 --- a/lib/ControlPanel.php +++ /dev/null @@ -1,1573 +0,0 @@ -(empty)'); - -// Permissions -define('CPP_ADD', 1 << 1); -define('CPP_EDIT', 1 << 2); -define('CPP_VIEW', 1 << 3); -define('CPP_DELETE', 1 << 4); -define('CPP_SEARCH', 1 << 4); - -// Pager -define('CPPAGER_RESULTS_PER_PAGE', 14); - -class ControlPanel -{ - private $_fields; - private $_tables; - private $_sections; - private $_db; - private $_wf; - private $_primaryKey; - private $_sortByField; - private $_linkField; - private $_permissions; - private $_selectBoundriesSql; - private $_insertBoundriesSql; - private $_deleteBoundriesSql; - private $_deleteBoundriesTable; - private $_showCurrencySums; - private $_callBacks; - private $_sortDesc; - private $_truncate; - private $_truncateID; - private $_fieldUrls; - private $_listViewLayout; - - - public function __construct() - { - $this->_tables = array(); - $this->_db = DatabaseConnection::getInstance(); - $this->_wf = new WebForm(); - $this->_sections = array(); - $this->_primaryKey = ''; - $this->_sortByField = ''; - $this->_permissions = 0; - $this->_selectBoundriesSql = ''; - $this->_insertBoundriesSql = ''; - $this->_deleteBoundriesSql = ''; - $this->_deleteBoundriesTable = ''; - $this->_linkField = ''; - $this->_showCurrencySums = false; - $this->_callBacks = array(); - $this->_sortDesc = true; - $this->_truncate = array(); - $this->_truncateID = 0; - $this->_fieldUrls = array(); - $this->_listViewLayout = ''; - } - - - public function getModal() - { - $pageState = intval($this->getPostValue('cpPageState')); - switch($pageState) - { - case CPPS_ADD: - if ($this->_permissions & CPP_ADD) - return $this->getWebForm(true); - else - return $this->getListView(); - case CPPS_VIEW: - if ($this->_permissions & CPP_VIEW) - return $this->getWebForm(false); - else - return $this->getListView(); - case CPPS_EDIT: - if ($this->_permissions & CPP_EDIT) - return $this->getWebForm(false); - else - return $this->getListView(); - case CPPS_DELETE: - if ($this->_permissions & CPP_DELETE) - return $this->getDeleteRow(); - else - return $this->getListView(); - default: - return $this->getListView(); - } - } - - public function getDeleteRow() - { - if ($this->_deleteBoundriesTable == '') - { - return $this->getException('Unable to Delete from this Table', 'We\'re sorry, but this table does ' - . 'not support delete operations.'); - } - - $uID = $this->getPostValue('uID'); - $uIDName = $this->getPostValue('uIDName'); - $sql = $this->getTablesSQL(sprintf('%s = %d', addslashes($uIDName), addslashes($uID))); - $rs = $this->_db->query($sql); - if ($rs && mysqli_num_rows($rs) > 0) - { - $row = mysqli_fetch_array($rs, MYSQLI_ASSOC); - if (!$row) - { - return $this->getException('Bad or expired identifier', 'The operation you attempted cannot complete ' - . 'because the unique identifier no longer exists. Did you perhaps use your browser\'s back ' - . 'button?'); - } - - $tableName = $this->_deleteBoundriesTable; - $sql = 'DELETE FROM ' . $tableName . ' WHERE '; - if (isset($this->_tables[$tableName])) - { - foreach($this->_tables[$tableName]['fields'] as $fieldName => $fieldData) - { - if ($fieldData['primaryKey']) - { - if (is_numeric($row[$fieldData['uniqueID']])) $keyVal = sprintf('%d', $row[$fieldData['uniqueID']]); - else $keyVal = '"' . addslashes($row[$fieldData['uniqueID']]) . '"'; - $sql .= sprintf('%s = %s', $fieldName, $keyVal); - } - } - } - $rs = $this->_db->query($sql); - if (!$rs) - { - return $this->getException('Unable to Delete', 'The operation you attempted cannot complete. ' - . 'We apologize for the inconvenience and will attempt to solve this issue as soon as ' - . 'possible.'); - } - } - - return $this->getListView(); - } - - public function getWebForm($addRecord = false) - { - $html = ''; - $infoHtml = ''; - if ($addRecord) - { - $this->_wf->setVerifyForm(false); - $row = array(); - } - else - { - $this->_wf->setVerifyForm(true); - - // This is an edit, lookup information - $uID = $this->getPostValue('uID'); - $uIDName = $this->getPostValue('uIDName'); - $sql = $this->getTablesSQL(sprintf('%s = %d', addslashes($uIDName), addslashes($uID))); - $rs = $this->_db->query($sql); - if (!$rs) - { - return $this->getListView(); - return $this->getException('Bad or expired identifier', 'The operation you attempted cannot complete ' - . 'because the unique identifier no longer exists. Did you perhaps use your browser\'s back ' - . 'button?'); - } - $row = mysqli_fetch_array($rs, MYSQLI_ASSOC); - if (!$row) - { - return $this->getListView(); - return $this->getException('Bad or expired identifier', 'The operation you attempted cannot complete ' - . 'because the unique identifier no longer exists. Did you perhaps use your browser\'s back ' - . 'button?'); - } - } - - $html .= sprintf('
', - substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) - ); - foreach($_GET as $name => $value) - { - if (!strcmp($name, 'cpPageState')) - $html .= sprintf('', - CPPS_LISTVIEW - ); - else if(!strcmp($name, 'a') || !strcmp($name, 'm') || !strcmp($name, 'siteID')) - $html .= sprintf('', - htmlspecialchars($name), htmlspecialchars($value) - ); - } - $html .= '
'; - $html .= ''; - if ($addRecord && $this->_permissions & CPP_ADD) - $html .= ''; - else if(!$addRecord && $this->_permissions & CPP_EDIT) - $html .= ''; - $html .= '
'; - $html .= '<-- Back to List' . $this->_wf->getImageButton('images/cp_add.gif', 'Add Record', 'cpEditForm') . '' . $this->_wf->getImageButton('images/cp_save.gif', 'Save Changes', 'cpEditForm') . '
'; - - $html .= sprintf('
', - substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) - ); - foreach($_GET as $name => $value) - { - $html .= sprintf('', - htmlspecialchars($name), htmlspecialchars($value) - ); - } - - // Build the webform - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (!isset($fieldData['section']) || count($fieldData['section']) == 0) continue; - if ($fieldData['section'][0] == CP_LISTVIEW && count($fieldData['section']) == 1) continue; - $this->_wf->addField($fieldData['webFormParams']['name'], - $fieldData['webFormParams']['caption'], $fieldData['webFormParams']['type'], - $fieldData['webFormParams']['required'], $fieldData['webFormParams']['size'], - $fieldData['webFormParams']['minlen'], $fieldData['webFormParams']['maxlen'], - $fieldData['webFormParams']['defaultValue'], $fieldData['webFormParams']['regex_test'], - $fieldData['webFormParams']['regex_fail'], $fieldData['webFormParams']['helpBody'], - $fieldData['webFormParams']['helpRules'] - ); - } - } - - if ($this->getPostValue('webFormPostBack') == '1') - { - $updateSql = array(); - list($fields, $errors) = $this->_wf->getValidatedFields(); - if (count($errors) > 0) - { - $infoHtml = '
' - . '
' - . '

There are a few problems:

' - . '
  • ' - . '

    ' - . implode('

  • ', $errors) - . '

'; - } - else - { - foreach($fields as $fieldName => $fieldValue) - { - $fieldValue = trim($fieldValue); - foreach($this->_tables as $subTableName => $subTableData) - { - foreach($subTableData['fields'] as $subFieldName => $subFieldData) - { - if (!strcmp($subFieldData['uniqueID'], $fieldName)) - { - if ($addRecord) - { - // this is an addition, build the SQL - if (!isset($updateSql[$subTableName])) $updateSql[$subTableName] = array('', ''); - $sqlFields = $updateSql[$subTableName][0]; - $sqlValues = $updateSql[$subTableName][1]; - if ($sqlFields != '') $sqlFields .= ', '; - $sqlFields .= $subFieldName; - if ($sqlValues != '') $sqlValues .= ', '; - $sqlValues .= $this->getFieldDBText($subFieldData, $fieldValue); - - $updateSql[$subTableName][0] = $sqlFields; - $updateSql[$subTableName][1] = $sqlValues; - - // populate the row for callbacks - $row[$fieldName] = $fieldValue; - } - else - { - // This is an edit and a field has been changed - if ($this->isFieldChange($row[$fieldName], $fieldValue, $subFieldData)) - { - if (!isset($updateSql[$subTableName])) $updateSql[$subTableName] = ''; - if ($updateSql[$subTableName] != '') $updateSql[$subTableName] .= ', '; - $updateSql[$subTableName] .= sprintf('%s.%s = %s', - $subTableName, $subFieldName, $this->getFieldDBText($subFieldData, $fieldValue) - ); - } - } - } - } - } - } - } - - if (count($updateSql) > 0) - { - $callBack = 0; - - if ($addRecord && (!$this->_permissions & CPP_ADD)) - return $this->getException('You cannot add records', - 'This table does not support adding new records.'); - if (!$addRecord && (!$this->_permissions & CPP_EDIT)) - return $this->getException('You cannot edit records', - 'This table does not support editting records.'); - - $updatedRows = 0; - foreach($updateSql as $tableName => $updateTableSql) - { - $ruleTableSql = ''; - $sql = ''; - if ($addRecord) - { - // Figure out the primary key to pass to a callback function - $callBackPrimaryKey = ''; - foreach($this->_tables[$tableName]['fields'] as $fieldName => $fieldData) - { - if ($fieldData['primaryKey']) - { - $callBackPrimaryKey = $fieldData['uniqueID']; - } - } - - if ($this->_insertBoundriesSql != '') - { - list($fieldName, $fieldValue) = explode('=', $this->_insertBoundriesSql); - $fieldName = trim($fieldName); - $fieldValue = trim($fieldValue); - } - // This is an addition (INSERT) - $sql = sprintf('INSERT INTO %s (%s%s) VALUES (%s%s)', - $tableName, $updateTableSql[0], - ($this->_insertBoundriesSql ? ', ' . $fieldName : ''), - $updateTableSql[1], - ($this->_insertBoundriesSql ? ', ' . $fieldValue : '') - ); - if (isset($this->_callBacks[CPP_ADD])) - { - $callBack = $this->_callBacks[CPP_ADD]; - } - } - else - { - // This is an edit (UPDATE) - // Figure out the primary key for this table and set a rule so only the current - // row is editted (when in edit mode) - foreach($this->_tables[$tableName]['fields'] as $fieldName => $fieldData) - { - if ($fieldData['primaryKey']) - { - if (is_numeric($row[$fieldData['uniqueID']])) $keyVal = sprintf('%d', $row[$fieldData['uniqueID']]); - else $keyVal = '"' . addslashes($row[$fieldData['uniqueID']]) . '"'; - $ruleTableSql = sprintf('%s = %s', $fieldName, $keyVal); - break; - } - } - - if ($ruleTableSql != '') - { - // attempt to write the changes to the database for this table - $sql = sprintf('UPDATE %s SET %s WHERE %s', - $tableName, $updateTableSql, $ruleTableSql - ); - if (isset($this->_callBacks[CPP_EDIT])) - { - $callBack = $this->_callBacks[CPP_EDIT]; - } - } - } - if ($sql != '') - { - $rs = $this->_db->query($sql); - if (!$rs) - { - return $this->getException('There was an error saving your changes', - 'An unexpected error has occured when trying to make the changes ' - . 'you made permanent. An administrator has been contacted and ' - . 'the problem will be looked into shortly. We appologize for the ' - . 'inconvenience.'); - } - else - { - $updatedRows += mysqli_affected_rows($this->_db->getConnection()); - if ($addRecord && $callBackPrimaryKey) - $row[$callBackPrimaryKey] = mysqli_insert_id($this->_db->getConnection()); - if ($callBack) - $callBack($row); - } - } - } - - if ($updatedRows > 0) - { - if ($addRecord) - { - $infoHtml .= "
\n"; - $infoHtml .= "You have added a record.\n
"; - $infoHtml .= "Do not refresh this page as it may result in a duplicate submission."; - $infoHtml .= "
\n"; - $infoHtml .= sprintf('', - substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) - ); - foreach($_GET as $name => $value) - { - if (!strcmp($name, 'cpPageState')) - $infoHtml .= sprintf('', - CPPS_LISTVIEW - ); - else if(!strcmp($name, 'a') || !strcmp($name, 'm') || !strcmp($name, 'siteID')) - $infoHtml .= sprintf('', - htmlspecialchars($name), htmlspecialchars($value) - ); - } - $infoHtml .= '
'; - $infoHtml .= '<-- Back to List'; - return $infoHtml; - } - else - { - $src = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?')+1); - CATSUtility::transferRelativeURI($src . '&cpChangesMade=1'); - } - } - } - } - - if (isset($_GET['cpChangesMade']) && $_GET['cpChangesMade'] == '1') - { - $infoHtml .= "
\n"; - $infoHtml .= "Your changes have been saved.\n"; - $infoHtml .= "
\n"; - $infoHtml .= "\n"; - } - - foreach($this->_sections as $sectionName => $sectionData) - { - if ($sectionName != CP_LISTVIEW) // Reserved for the list view formatting - { - $sectionFields = ''; - $prefillData = array(); - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (isset($fieldData['section']) && in_array($sectionName, $fieldData['section'])) - { - if ($sectionFields != '') $sectionFields .= '[NL]'; - $sectionFields .= sprintf('[%s]', $fieldData['uniqueID']); - - if (!$addRecord) - { - // prefill the field with existing data for edits - $rawData = $this->getFieldInputText($fieldData, $row[$fieldData['uniqueID']], ''); - $prefillData[$fieldData['uniqueID']] = $rawData; - } - } - } - } - - if (!$addRecord) - $this->_wf->setValidatedFields($prefillData); - - // Display the webform - if ($sectionData['webFormLayout'] == '') - $this->_wf->setLayout($sectionFields); - else - $this->_wf->setLayout($sectionData['webFormLayout']); - $html .= "
\n"; - $html .= "" . $sectionData['caption'] . "\n"; - - $contentsHtml = $sectionData['sectionLayout']; - $contentsHtml = str_replace('[WebForm]', $this->_wf->getForm('cellpadding="0" cellspacing="4"'), $contentsHtml); - - // Allow users (on edits) to specify EasyTags, so they can retrieve Database field values - // when using [field_name] tags in the sectionLayout - if (!$addRecord) - { - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (isset($row[$fieldData['uniqueID']])) - $contentsHtml = str_replace(sprintf('[%s]', $fieldData['uniqueID']), $row[$fieldData['uniqueID']], $contentsHtml); - } - } - } - - $html .= $contentsHtml; - $html .= "\n
\n

\n"; - } - } - - if ($addRecord && $this->_permissions & CPP_ADD) - $html .= $this->_wf->getButton('Add Record', 'cpEditForm'); - else if(!$addRecord && $this->_permissions & CPP_EDIT) - $html .= $this->_wf->getButton('Save Changes', 'cpEditForm'); - //if ($this->_permissions & CPP_DELETE && $this->_deleteBoundriesTable != '' && !$addRecord) - // $html .= $this->_wf->getButton('Delete', 'cpDeleteForm'); - - // add css and javascript on-the-fly - $html = sprintf("\n\n%s%s", - $this->getCSS(), $this->getWebFormJavaScript(), $infoHtml, $html - ); - - return $html; - } - - private function isFieldChange($dbText, $newText, $fieldData) - { - switch($fieldData['webFormParams']['type']) - { - case WFT_BOOLEAN: - if ((!strcasecmp($newText, 'true') && $dbText) || - (!strcasecmp($newText, 'false') && !$dbText)) - return false; - else - return true; - break; - case WFT_CC_NUMBER: - // user hasn't changed credit card, it was just masked (not on ssl) - if (preg_match("/^[X]{4}[\-]?[X]{4}[\-]?[X]{4}[\-]?[0-9]{4}$/", $newText)) - return false; - else if (!strlen($dbText) && !strlen($newText)) - { - return false; - } - else if (strcmp(EncryptionUtility::decryptCreditCardNumber($dbText), $newText)) - { - return true; - } - else - { - return false; - } - break; - case WFT_CURRENCY: - $newText = str_replace('$', '', $newText); - if (floatval($newText) != floatval($dbText)) - return true; - else - return false; - break; - case WFT_CC_EXPIRATION: - if (strlen(trim($newText)) == 0 && strlen(trim($dbText)) == 0) - return false; - if (strlen(trim($newText)) > 0) - { - list($month, $year) = explode('/', $newText); - if (strlen(strval($year)) == 2) $year += 2000; - $newTime = strtotime(sprintf('%04d-%02d-01', $year, $month)); - } - else - { - $newTime = 0; - } - - if ($newTime != strtotime($dbText)) - return true; - else - return false; - break; - case WFT_DATE: - if (strtotime($newText) != strtotime($dbText)) - return true; - else - return false; - break; - default: - if (strcmp($dbText, $newText)) - return true; - else - return false; - break; - } - } - - public function getWebFormJavaScript() - { - return $this->_wf->getJavaScript(); - } - - public function getListViewJavaScript() - { - ob_start(); - // Add JavaScript for mouseover on rows - ?> - var lockMarking = false; - var cpHideMouseOverRow = ''; - function cpMouseOverRow(id, tf) - { - var obj; - - if (lockMarking == true) return; - - if (tf && cpHideMouseOverRow != id) - { - _tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - ?> - obj = document.getElementById('cp_' + id); - obj.style.backgroundColor = '#e0e0e0'; - - // for admin.row - obj = document.getElementById('cp_adminDOTrow' + id); - obj.style.backgroundColor = '#e0e0e0'; - } - else - { - _tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - ?> - obj = document.getElementById('cp_' + id); - if (id % 2) - obj.style.backgroundColor = '#f0f0f0'; - else - obj.style.backgroundColor = '#ffffff'; - - obj = document.getElementById('cp_adminDOTrow' + id); - if (id % 2) - obj.style.backgroundColor = '#f0f0f0'; - else - obj.style.backgroundColor = '#ffffff'; - } - } - function cpMarkForDelete(id, tf) - { - var obj; - if (tf) - { - lockMarking = true; - _tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - ?> - obj = document.getElementById('cp_' + id); - obj.style.backgroundColor = '#ffd8d8'; - - // for admin.row - obj = document.getElementById('cp_adminDOTrow' + id); - obj.style.backgroundColor = '#e0e0e0'; - } - else - { - lockMarking = false; - _tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - ?> - obj = document.getElementById('cp_' + id); - if (id % 2) - obj.style.backgroundColor = '#f0f0f0'; - else - obj.style.backgroundColor = '#ffffff'; - - obj = document.getElementById('cp_adminDOTrow' + id); - if (id % 2) - obj.style.backgroundColor = '#f0f0f0'; - else - obj.style.backgroundColor = '#ffffff'; - } - } - _wf->getCSS(); - } - - public function getListView() - { - $currencySumData = array(); - - // ******************** SEARCH *********************** - if (isset($_GET['cpSearchString']) || isset($_POST['cpSearchString'])) - { - $searchString = $this->getPostValue('cpSearchString'); - $searchSql = ''; - - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - if ($searchSql != '') $searchSql .= 'OR '; - $searchSql .= sprintf('%s.%s LIKE "%%%s%%"', - $tableName, $fieldName, - addslashes($searchString) - ); - } - } - } - if ($searchSql != '') - { - $searchSql = '(' . $searchSql . ')'; - } - } - else - { - $searchString = ''; - $searchSql = ''; - } - - - // ********************** SUMS *************************** - if ($this->_showCurrencySums) - { - $currencySql = ''; - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section']) && $fieldData['webFormType'] == WFT_CURRENCY) - { - if ($currencySql != '') $currencySql .= ' '; - $currencySql .= sprintf('SUM(%s.%s) AS %s', - $tableName, $fieldName, $fieldData['uniqueID'] - ); - } - } - } - if ($currencySql != '') - { - $rs = $this->_db->query($sql = $this->getTablesSQL($searchSql, '', $currencySql)); - $currencySums = mysqli_fetch_array($rs, MYSQLI_ASSOC); - } - } - - // ********************** PAGER ************************** - $pager_ResultsPerPage = $this->getPostValue('cp_ResultsPerPage'); - $pager_CurrentPage = $this->getPostValue('cp_CurrentPage'); - - if ($pager_ResultsPerPage == '') - $pager_ResultsPerPage = CPPAGER_RESULTS_PER_PAGE; - else - $pager_ResultsPerPage = intval($pager_ResultsPerPage); - - if ($pager_CurrentPage == '') - $pager_CurrentPage = 0; - else - $pager_CurrentPage = intval($pager_CurrentPage) - 1; - - // get the records count - $rs = $this->_db->query($sql = $this->getTablesSQL($searchSql, '', 'COUNT(*)')); - $rsCount = intval(mysqli_fetch_row($rs)); - $numPages = ceil($rsCount / $pager_ResultsPerPage); - if ($pager_CurrentPage >= $numPages) $pager_CurrentPage = $numPages - 1; - if ($pager_CurrentPage < 0) $pager_CurrentPage = 0; - if ($numPages > 1) - $limitSql = sprintf('%d OFFSET %d', $pager_ResultsPerPage, $pager_CurrentPage * $pager_ResultsPerPage); - else - $limitSql = ''; - - - $sql = $this->getTablesSQL($searchSql, $limitSql); - $rs = $this->_db->query($sql, $pager_ResultsPerPage, $pager_CurrentPage); - if (!$rs) - { - echo $sql; - return $this->getException('Unable to view', 'We\'re sorry, but an internal error has occurred and ' - . 'we are unable to show you the information you requested. This will be looked into as soon ' - . 'as possible.'); - } - $infoHtml = ''; - $headerHtml = ''; - $headerComplete = false; - $fieldOffset = true; - - $rowNum = 0; - while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) - { - $numColumns = 0; - $infoHtml .= "\n"; - if ($headerComplete == false) - $headerHtml .= "\n"; - - $myRow = array('admin.row' => ''); - $headerRow = array('admin.row' => ''); - - // for highlighting of mouseover rows - $highlightJS = array( - 'onmouseover' => sprintf('cpMouseOverRow(\'%d\', true);', $rowNum), - 'onmouseout' => sprintf('cpMouseOverRow(\'%d\', false);', $rowNum) - ); - $highlightJSFlat = sprintf('onmouseover="%s" onmouseout="%s"', - $highlightJS['onmouseover'], $highlightJS['onmouseout'] - ); - - // Print each field in the ListView section - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (!strcmp($tableData['primaryKey'], $fieldName)) - { - $uniqueRowIDName = $tableName . '.' . $fieldName; - $uniqueRowID = $row[$fieldData['uniqueID']]; - } - } - - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - if (!isset($headerRow[$fieldData['uniqueID']])) $headerRow[$fieldData['uniqueID']] = ''; - if (!isset($myRow[$fieldData['uniqueID']])) $myRow[$fieldData['uniqueID']] = ''; - - $numColumns++; - switch ($fieldData['webFormType']) - { - case WFT_BOOLEAN: - $textAlign = 'center'; - break; - case WFT_DATE: case WFT_CURRENCY: - $textAlign = 'right'; - break; - default: - $textAlign = 'left'; - break; - } - if ($headerComplete == false) - $headerRow[$fieldData['uniqueID']] .= sprintf('' - . '%s%s', - (!strcmp($this->_sortByField, $fieldData['uniqueID']) ? 'Sorted' : ''), - $textAlign, - $_SERVER['REQUEST_URI'], - (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?'), - $fieldData['uniqueID'], - $this->_sortDesc ? 'false' : 'true', - $fieldData['caption'], - (($this->_sortDesc && !strcmp($this->_sortByField, $fieldData['uniqueID'])) ? '' : '') // for showing desc - ); - - $viewUrl = sprintf('%s%scpPageState=%d&uID=%d&uIDName=%s', - $_SERVER['REQUEST_URI'], - (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?'), - CPP_EDIT, $uniqueRowID, $uniqueRowIDName - ); - - // Build the row display - $td = array( - 'id' => sprintf('cp_%s%d', $fieldData['uniqueID'], $rowNum), - 'onclick' => sprintf('document.location.href=\'%s\';', $viewUrl), - 'class' => sprintf('%s', ($fieldOffset ? 'cpField1' : 'cpField2')), - 'style' => 'cursor: pointer;', - 'valign' => 'center', - 'align' => $textAlign - ); - $td = array_merge($td, $highlightJS); - $td_text = $this->getFieldHtmlText($fieldData, $row[$fieldData['uniqueID']], CPSTR_EMPTY_FIELD); - - // Process the row display override (if exists) to modify the row's output - if (isset($this->_callBacks['td']) && ($func = $this->_callBacks['td'])) - { - if (is_array($results = $func($fieldData['uniqueID'], $td, $td_text, $row))) - { - list($td, $td_text) = $results; - } - } - - $td_html = sprintf('%s%s%s%s%s', - (!strcmp($this->_linkField, $fieldData['uniqueID']) ? '' : ''), - (isset($this->_fieldUrls[$fieldData['uniqueID']]) ? '' : ''), - $td_text, - (isset($this->_fieldUrls[$fieldData['uniqueID']]) ? '

' - . $this->getFieldLinkText($row, $this->_fieldUrls[$fieldData['uniqueID']]['comments']) . '
' : ''), - (!strcmp($this->_linkField, $fieldData['uniqueID']) ? '' : '') - ); - - $td_final = ''; - foreach($td as $tag => $val) - { - if ($td_final != '') $td_final .= ' '; - $td_final .= sprintf('%s="%s"', $tag, $val); - } - $myRow[$fieldData['uniqueID']] .= sprintf('%s', - $td_final, - $td_html - ); - } - } - } - // permission-accessible functions - if ($this->_permissions & CPP_EDIT || $this->_permissions & CPP_DELETE) - { - if ($headerComplete == false) - $headerRow['admin.row'] .= ''; - $myRow['admin.row'] .= sprintf('', - $highlightJSFlat, - $rowNum, - ($fieldOffset ? 'cpField1' : 'cpField2') - ); - $myRow['admin.row'] .= ''; - if ($this->_permissions & CPP_EDIT) - { - if ($headerComplete == false) - $headerRow['admin.row'] .= ' '; - $myRow['admin.row'] .= sprintf('', - $_SERVER['REQUEST_URI'], - (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?'), - CPP_EDIT, $uniqueRowID, $uniqueRowIDName - ); - $existingSections = true; - } - if ($this->_permissions & CPP_DELETE && $this->_deleteBoundriesTable != '') - { - if ($headerComplete == false) - $headerRow['admin.row'] .= ' '; - $myRow['admin.row'] .= sprintf('', - $rowNum, - $_SERVER['REQUEST_URI'], - (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?'), - CPP_DELETE, $uniqueRowID, $uniqueRowIDName, $rowNum - ); - $existingSections = true; - } - if ($this->_permissions & CPP_DELETE) - { - - } - $myRow['admin.row'] .= '
' - . '
'; - if ($headerComplete == false) - $headerRow['admin.row'] .= ''; - $myRow['admin.row'] .= ''; - } - - if ($headerComplete == false) - { - foreach ($this->_sections[CP_LISTVIEW]['fieldOrder'] as $uniqueID) - if (isset($headerRow[$uniqueID])) - $headerHtml .= $headerRow[$uniqueID]; - $headerHtml .= $headerRow['admin.row']; - } - foreach ($this->_sections[CP_LISTVIEW]['fieldOrder'] as $uniqueID) - if (isset($myRow[$uniqueID])) - $infoHtml .= $myRow[$uniqueID]; - $infoHtml .= $myRow['admin.row']; - - $infoHtml .= "\n"; - if ($headerComplete == false) - $headerHtml .= "\n"; - $headerComplete = true; - $fieldOffset = !$fieldOffset; - $rowNum++; - } - - if ($this->_showCurrencySums && $rsCount > 0 && $currencySql != '') - { - $infoHtml .= sprintf('%d TOTAL ROWS', - $numColumns+1, $rsCount - ); - - $infoHtml .= "\n"; - $myRow = array(); - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - // Check if it's an active field and if it's in the ListView section - if (isset($fieldData['activeField']) && $fieldData['activeField'] == true && - isset($fieldData['section']) && is_array($fieldData['section']) && - in_array(CP_LISTVIEW, $fieldData['section'])) - { - if ($fieldData['webFormType'] == WFT_CURRENCY && isset($currencySums[$fieldData['uniqueID']])) - { - $myRow[$fieldData['uniqueID']] = sprintf('$%s', - number_format($currencySums[$fieldData['uniqueID']], 2) - ); - } - else - { - $myRow[$fieldData['uniqueID']] = ' '; - } - } - } - } - - foreach ($this->_sections[CP_LISTVIEW]['fieldOrder'] as $uniqueID) - if (isset($myRow[$uniqueID])) - $infoHtml .= $myRow[$uniqueID]; - // for admin.row: - $infoHtml .= " \n"; - } - - // Display pager if needed - $pagerHtml = ''; - if ($numPages > 1) - { - if (strpos($_SERVER['REQUEST_URI'], '?') !== false) - $url = $_SERVER['REQUEST_URI'] . '&'; - else - $url = $_SERVER['REQUEST_URI'] . '?'; - $url .= sprintf('cp_ResultsPerPage=%d&', $pager_ResultsPerPage); - - // next/prev page links - if ($pager_CurrentPage > 0) - $pagerHtml .= sprintf('Previous Page', - $url, $pager_CurrentPage - ); - if ($pager_CurrentPage < $numPages-1) - { - if ($pager_CurrentPage > 0) $pagerHtml .= ' | '; - $pagerHtml .= sprintf('Next Page', - $url, $pager_CurrentPage+2 - ); - } - $pagerHtml .= '
Page: '; - - // list of pages - for($page = 0; $page < $numPages; $page++) - { - if ($page != $pager_CurrentPage) - $pagerHtml .= sprintf('%d ', - $url, $page+1, $page+1 - ); - else - $pagerHtml .= sprintf('%d ', $page+1); - } - } - - if ($this->_permissions & CPP_ADD) - { - $pagerHtml .= sprintf('

Add (+)', - $_SERVER['REQUEST_URI'], - (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?'), - CPPS_ADD - ); - } - - $titleHtml = ''; - $searchHtml = ''; - if ($this->_permissions & CPP_SEARCH) - { - if ($searchString != '') - $titleHtml .= 'Found ' . number_format($rsCount,0) . ' ' - . 'result' . ($rsCount != 1 ? 's' : '') . ' for "' . $searchString . '"

'; - $searchHtml .= '

'; - $searchHtml .= $this->getForm('cpSearch'); - $searchHtml .= ''; - $searchHtml .= '
'; - } - - $listViewHtml = sprintf("\n%s\n%s\n%s\n
\n
\n%s%s
", - $this->getListViewJavaScript(), $titleHtml, $headerHtml, $infoHtml, $pagerHtml, $searchHtml - ); - - return str_replace('[ListView]', $listViewHtml, $this->_listViewLayout); - } - - private function getForm($name) - { - $html = sprintf('
', - substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) - ); - foreach($_GET as $name => $value) - { - if (!strcmp($name, 'cpPageState')) - $html .= sprintf('', - CPPS_LISTVIEW - ); - else if(!strcmp($name, 'a') || !strcmp($name, 'm') || !strcmp($name, 'siteID')) - $html .= sprintf('', - htmlspecialchars($name), htmlspecialchars($value) - ); - } - return $html; - } - - private function getFieldDBText($fieldData, $text) - { - $text = trim($text); - if (strlen($text) == 0) - return 'NULL'; - switch($fieldData['webFormType']) - { - case WFT_CC_EXPIRATION: - list($expireMonth, $expireYear) = explode('/', $text); - return '"' . sprintf('%s-%s-01', $expireYear, $expireMonth) . '"'; - case WFT_CC_NUMBER: - return '"' . addslashes(EncryptionUtility::encryptCreditCardNumber($text)) . '"'; - case WFT_BOOLEAN: - return (!strcasecmp($text, 'true') ? '1' : '0'); - case WFT_CURRENCY: - return sprintf('%.2f', floatval($text)); - case WFT_DATE: - return '"' . date('c', strtotime($text)) . '"'; - default: - return '"' . addslashes($text) . '"'; - } - } - - private function getFieldInputText($fieldData, $rawData) - { - if (strlen(trim($rawData)) == 0) - return ''; - switch($fieldData['webFormType']) - { - case WFT_CC_EXPIRATION: - return date('n/Y', strtotime($rawData)); - case WFT_BOOLEAN: - if (intval($rawData) != 0) return 'true'; - else return 'false'; - case WFT_CC_NUMBER: - return EncryptionUtility::decryptCreditCardNumber($rawData); - case WFT_DATE: - return date('n/j/Y', strtotime($rawData)); - case WFT_CURRENCY: - return '$' . number_format(floatval($rawData), 2, '.', ','); - default: - return $rawData; - } - } - - private function getFieldLinkText($row, $rawData) - { - foreach($row as $name => $value) - { - $rawData = str_replace(sprintf('[%s]', $name), $value, $rawData); - } - return $rawData; - } - - private function getFieldHtmlText($fieldData, $rawData) - { - if (strlen(trim($rawData)) == 0) - return CPSTR_EMPTY_FIELD; - switch($fieldData['webFormType']) - { - case WFT_EMAIL: - return sprintf('%s', $rawData, $rawData); - case WFT_BOOLEAN: - if (intval($rawData) != 0) return 'true'; - else return 'false'; - case WFT_CC_NUMBER: - return EncryptionUtility::decryptCreditCardNumber($rawData); - case WFT_DATE: - return date('n/j/Y', strtotime($rawData)); - case WFT_CURRENCY: - return '$' . number_format(floatval($rawData), 2, '.', ','); - default: - // Check for truncate - if (isset($this->_truncate[$fieldData['uniqueID']])) - { - $truncated = substr($rawData, 0, $this->_truncate[$fieldData['uniqueID']]); - if (strlen($truncated) != strlen($rawData)) - { - $id = $this->_truncateID++; - return sprintf('' - . '%s ...' - . '', - $fieldData['uniqueID'], $id, - $fieldData['uniqueID'], $id, - $truncated, - $fieldData['uniqueID'], $id, - $this->_truncate[$fieldData['uniqueID']] * 7, - $rawData - ); - } - } - return $rawData; - } - } - - public function addSection($name, $caption, $fields, $webFormLayout = '', $sectionLayout = '[WebForm]') - { - if ($name == CP_LISTVIEW) - { - if (!strcmp($sectionLayout, '[WebForm]')) - $this->_listViewLayout = '[ListView]'; - else - $this->_listViewLayout = $sectionLayout; - } - $this->_sections[$name] = array( - 'caption' => $caption, - 'webFormLayout' => $webFormLayout, - 'sectionLayout' => $sectionLayout, - 'fieldOrder' => $fields - ); - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (in_array($fieldName, $fields) || in_array($fieldData['uniqueID'], $fields)) - { - if (isset($this->_tables[$tableName]['fields'][$fieldName]['section'])) - $this->_tables[$tableName]['fields'][$fieldName]['section'][] = $name; - else - $this->_tables[$tableName]['fields'][$fieldName]['section'] = array( $name ); - } - } - } - } - - public function addField($name, $caption, $type, $required = false, $size = 16, $minlen = 0, $maxlen = -1, - $defaultValue = -1, $regex_test = '', $regex_fail = '', $helpBody = -1, - $helpRules = '') - { - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if (!strcmp($fieldName, $name) || (isset($fieldData['uniqueID']) && !strcmp($fieldData['uniqueID'], $name))) - { - // Set some fields automatically using database data - if (!$fieldData['allowNull']) $required = true; - if (preg_match("/varchar\(([0-9]+)\)/", $fieldData['type'], $matches)) - { - if ($maxlen == -1) $maxlen = intval($matches[1]); - } - if ($defaultValue == -1) - $defaultValue = $fieldData['defaultValue']; - if ($helpBody == -1) - $helpBody = $fieldData['description']; - $this->_tables[$tableName]['fields'][$fieldName]['activeField'] = true; - $this->_tables[$tableName]['fields'][$fieldName]['webFormType'] = $type; - $this->_tables[$tableName]['fields'][$fieldName]['caption'] = $caption; - $this->_tables[$tableName]['fields'][$fieldName]['webFormParams'] = array( - 'name' => $name, 'caption' => $caption, 'type' => $type, 'required' => $required, - 'size' => $size, 'minlen' => $minlen, 'maxlen' => $maxlen, 'defaultValue' => $defaultValue, - 'regex_test' => $regex_test, 'regex_fail' => $regex_fail, 'helpBody' => $helpBody, - 'helpRules' => $helpRules - ); - return 1; - } - } - } - return -1; - } - - /** - * Builds an SQL query for returning all fields from all the tables - * in the $_tables which are parsed MySQL tables. - */ - public function getTablesSQL($relationshipSql = '', $limitSql = '', $selectSql = '') - { - $fieldsSql = ''; - $tablesSql = ''; - $relationshipsFound = 1; - - // check for sort-by field being passed by URI - if (isset($_GET['cpSortByField']) || isset($_POST['cpSortByField'])) - { - $this->setSortByField($this->getPostValue('cpSortByField')); - } - // Sort ASC/DESC - if (isset($_GET['cpSortDesc']) || isset($_POST['cpSortDesc'])) - { - $this->_sortDesc = (!strcmp($this->getPostValue('cpSortDesc'), 'false') ? false : true); - } - - foreach($this->_tables as $tableName => $tableData) - { - foreach($tableData['fields'] as $fieldName => $fieldData) - { - if ((isset($fieldData['activeField']) && $fieldData['activeField'] == true) || !strcmp($tableData['primaryKey'], $fieldName)) - { - if ($fieldsSql != '') $fieldsSql .= ', '; - $fieldsSql .= sprintf(' %s.%s as %s', - $tableName, $fieldName, - $fieldData['uniqueID'] - ); - } - } - - foreach ($this->_tables as $subTableName => $subTableData) - { - if (!strcmp($subTableName, $tableName)) continue; // do not check the same table! - - foreach ($subTableData['fields'] as $subFieldName => $subFieldData) - { - if (!strcmp($tableData['primaryKey'], $subFieldName)) - { - if ($relationshipSql != '') $relationshipSql .= ' AND '; - $relationshipSql .= sprintf(' %s.%s = %s.%s', - $subTableName, $subFieldName, $tableName, $tableData['primaryKey'] - ); - $relationshipsFound++; - } - } - } - - if ($tablesSql != '') $tablesSql .= ', '; - $tablesSql .= $tableName; - } - - if ($relationshipsFound != count($this->_tables)) - { - return -1; - } - - $whereSql = ''; - if ($this->_selectBoundriesSql != '') - { - if ($whereSql != '') $whereSql .= ' AND '; - $whereSql .= $this->_selectBoundriesSql; - } - if ($relationshipSql != '') - { - if ($whereSql != '') $whereSql .= ' AND '; - $whereSql .= $relationshipSql; - } - - if ($this->_sortDesc) - $sort = ' DESC '; - else - $sort = ' '; - - $sql = sprintf('SELECT %s FROM %s %s%s%s%s%s%s%s', - ($selectSql != '' ? $selectSql : $fieldsSql), - $tablesSql, - ($whereSql != '' ? 'WHERE ' : ''), - $whereSql, - ($this->_sortByField != '' && $selectSql == '' ? ' ORDER BY ' : ''), - ($selectSql == '' ? $this->_sortByField : ''), - ($this->_sortByField != '' && $selectSql == '' ? $sort : ''), - ($limitSql != '' ? ' LIMIT ' : ''), - $limitSql - ); - - return $sql; - } - - /** - * Adds and parses the format of a MySQL table (obtains primary key, field rules, etc.) - * - * @param string $name MySQL table name - */ - public function addMySQLTable($name) - { - $this->_tables[$name] = array(); - $this->_tables[$name]['fields'] = array(); - // Fetch the fields from the table - $rs = $this->_db->query('SHOW FIELDS FROM ' . $name); - while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) - { - $this->_tables[$name]['fields'][$row['Field']] = array( - 'type' => $row['Type'], - 'allowNull' => (strcmp($row['Null'], 'NO') ? true : false), - 'defaultValue' => $row['Default'], - 'description' => $row['Extra'], - 'uniqueID' => $this->getConvertUnderscoreToCamel($name . '_' . $row['Field']), - 'primaryKey' => (!strcmp($row['Key'], 'PRI') ? true : false) - ); - if (!strcmp($row['Key'], 'PRI')) - { - $uniqueID = $this->_tables[$name]['fields'][$row['Field']]['uniqueID']; - if ($this->_primaryKey == '') - $this->_primaryKey = $uniqueID; - $this->_tables[$name]['primaryKey'] = $row['Field']; - } - } - } - - public function printTables() - { - print_r($this->_tables); - } - - private function getConvertUnderscoreToCamel($text) - { - for ($x = 0, $out = ''; $x < strlen($text); $x++) - { - if ($text[$x] == '_') - $out .= strtoupper($text[++$x]); - else - $out .= $text[$x]; - } - return $out; - } - - private function getConvertCamelToUnderscore($text) - { - for ($x = 0, $out = ''; $x < strlen($text); $x++) - { - if (strtoupper($text[$x]) == $text[$x]) - { - $out .= '_' . strtolower($text[$x]); - $y = $x; - while (($x+1) < strlen($text) && strtoupper($text[$x+1]) == $text[$x+1]) - $out .= strtolower($text[++$x]); - if ($y != $x) - { - $out = substr($out, 0, -1) . '_' . strtolower($text[$x]); - } - } - else - { - $out .= $text[$x]; - } - } - return $out; - } - - public static function getPostValue($name) - { - if (isset($_GET[$name])) return $_GET[$name]; - else if(isset($_POST[$name])) return $_POST[$name]; - else return ''; - } - - public function setFieldUrl($field, $url, $comments) - { - $this->_fieldUrls[$field] = array( 'url' => $url, 'comments' => $comments ); - } - - public function setTruncate($field, $size) - { - $this->_truncate[$field] = $size; - } - - public function addCallBack($mode, $val) - { - $this->_callBacks[$mode] = $val; - } - - public function setShowCurrencySums($tf) - { - return ($this->_showCurrencySums = $tf); - } - - public function setSelectBoundriesSQL($sql) - { - return ($this->_selectBoundriesSql = $sql); - } - - public function setInsertBoundriesSQL($sql) - { - return ($this->_insertBoundriesSql = $sql); - } - - public function setDeleteBoundriesSQL($sql) - { - return ($this->_deleteBoundriesSql = $sql); - } - - public function setDeleteBoundriesTable($table) - { - return ($this->_deleteBoundriesTable = $table); - } - - public function setPermissions($x) - { - $this->_permissions = $x; - } - - public function setSortByField($name) - { - return ($this->_sortByField = $name); - } - - public function getException($title, $message) - { - return sprintf('%s
%s', $title, $message); - } - - public function setLinkField($field) - { - return ($this->_linkField = $field); - } -} -?> diff --git a/lib/DefaultQuestionnaires.php b/lib/DefaultQuestionnaires.php deleted file mode 100755 index c98dd66ea..000000000 --- a/lib/DefaultQuestionnaires.php +++ /dev/null @@ -1,206 +0,0 @@ -_defaultQuestionnaires = array( - array( - 'title' => 'Sample IT Questionnaire', - 'description' => 'Please answer the following questions:', - 'isActive' => true, - 'questions' => array( - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_RADIO, - 'questionText' => 'Are you at least 18 years of age?', - 'questionPosition' => 1, - 'answers' => array( - array( - 'answerText' => 'Yes', - 'answerPosition' => 1 - ), - array( - 'answerText' => 'No', - 'answerPosition' => 2, - 'actionNotes' => 'Under 18' - ) - ) - ), - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_RADIO, - 'questionText' => 'Are you a resident of the U.S. or permitted to work in the U.S.?', - 'questionPosition' => 2, - 'answers' => array( - array( - 'answerText' => 'Yes', - 'answerPosition' => 1, - 'actionNotes' => 'Authorized to work in the U.S.', - ), - array( - 'answerText' => 'No', - 'answerPosition' => 2, - 'actionNotes' => 'NOT AUTHORIZED to work in the U.S.', - ) - ) - ), - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_SELECT, - 'questionText' => 'How would you rate your experience level?', - 'questionPosition' => 3, - 'answers' => array( - array( - 'answerText' => 'Junior', - 'answerPosition' => 1, - 'actionNotes' => 'Rates self as junior-level' - ), - array( - 'answerText' => 'Intermediate', - 'answerPosition' => 2, - 'actionNotes' => 'Rates self as intermediate-level' - ), - array( - 'answerText' => 'Expert', - 'answerPosition' => 3, - 'actionNotes' => 'Rates self as expert-level' - ) - ) - ), - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_CHECKBOX, - 'questionText' => 'Which languages do you have experience with?', - 'questionPosition' => 4, - 'answers' => array( - array( - 'answerText' => ($ans = 'C/C++'), - 'answerPosition' => 1, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'PHP'), - 'answerPosition' => 2, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Perl'), - 'answerPosition' => 3, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Java'), - 'answerPosition' => 4, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Python'), - 'answerPosition' => 5, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Ruby'), - 'answerPosition' => 6, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = '.NET'), - 'answerPosition' => 7, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Visual Basic'), - 'answerPosition' => 8, - 'actionKeySkills' => $ans - ) - ) - ), - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_CHECKBOX, - 'questionText' => 'Which databases do you have experience with?', - 'questionPosition' => 5, - 'answers' => array( - array( - 'answerText' => ($ans = 'MySQL'), - 'answerPosition' => 1, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'PostgreSQL'), - 'answerPosition' => 2, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Microsoft SQL Server'), - 'answerPosition' => 3, - 'actionKeySkills' => $ans - ), - array( - 'answerText' => ($ans = 'Oracle'), - 'answerPosition' => 4, - 'actionKeySkills' => $ans - ) - ) - ), - array( - 'questionType' => QUESTIONNAIRE_QUESTION_TYPE_SELECT, - 'questionText' => 'Are you willing to relocate?', - 'questionPosition' => 6, - 'answers' => array( - array( - 'answerText' => 'Yes', - 'answerPosition' => 1, - 'actionCanRelocate' => 1 - ), - array( - 'answerText' => 'Yes, with a moving allowance', - 'answerPosition' => 2, - 'actionCanRelocate' => 1, - 'actionNotes' => 'Requires moving allowance' - ), - array( - 'answerText' => 'No', - 'answerPosition' => 3, - 'actionCanRelocate' => 0 - ) - ) - ), - ) - ) - ); - } - - public function get() - { - return $this->_defaultQuestionnaires; - } -} - -?> diff --git a/lib/Display.php b/lib/Display.php deleted file mode 100755 index b58ad4094..000000000 --- a/lib/Display.php +++ /dev/null @@ -1,236 +0,0 @@ -_siteID = $siteID; - $this->_profileLib = $profileLib; - $this->_profilePage = $profilePage; - $this->_db = DatabaseConnection::getInstance(); - } - - /** - * Get the profile's title text for a column name. - * - * @param string Column name (i.e.: first_name) - * @return string Title text (i.e.: First Name) - */ - public function getTitleText($columnName) - { - return $this->_profileLib->getTitleText(false, $columnName); - } - - /** - * Get all information about a column name. - * - * @param string Column name (i.e.: first_name) - * @return array - */ - public function getField($columnName) - { - return $this->_profileLib->getField(false, $this->_profilePage['page'], $columnName); - } - - private function getTemplate($template, $flags = array()) - { - $templateFile = sprintf( - './profile/%s/%s.tpl', - $this->_profileLib->getProfile(), - $template - ); - - if (@file_exists($templateFile)) - { - $templateContents = @file_get_contents($templateFile); - foreach ($flags as $flag => $value) - { - $templateContents = str_replace('<'.$flag.'>', $value, $templateContents); - } - } - else - { - $templateContents = ''; - } - - return $templateContents; - } - - public function startTable() - { - global $profileStylesheet; - // Check if the current profile's style has been included, include if it hasn't - $sheet = $this->_profileLib->getProfileStylesheet(); - if ($profileStylesheet === false || strcmp($profileStylesheet, $sheet)) - { - echo sprintf( - '', - TemplateUtility::getVersionedAssetURL($sheet) - ); - $profileStylesheet = $sheet; - } - - $this->_table = array(); - $this->_rowIndex = $this->_columnIndex = 0; - $this->_currentColumn = false; - } - - public function endTable() - { - $pageContent = $this->getTemplate('page'); - list($pageTopContent, $pageBottomContent) = explode('', $pageContent); - - $sectionContent = $this->getTemplate('pageSection', - array('sectionWidth' => $this->_profilePage['columnWidth']) - ); - list($sectionTopContent, $sectionBottomContent) = explode('', $sectionContent); - - $columnContent = $this->getTemplate('pageColumn'); - - $fields = $this->_profileLib->getPageFields( - $this->_profileLib->getProfileID(), - $this->_profilePage['page'] - ); - - echo $pageTopContent; - - for ($fieldIndex = 0, $curColumn = -1, $inSection = false; - $fieldIndex < count($fields); - $fieldIndex++) - { - $field = $fields[$fieldIndex]; - - if (!isset($this->_table[$field['columnName']])) - { - continue; - } - - if ($curColumn != $field['xPosition']) - { - $curColumn = $field['xPosition']; - - if ($inSection) - { - echo $sectionBottomContent; - } - - echo $sectionTopContent; - $inSection = true; - } - - $data = $columnContent; - $data = str_replace('', $this->_table[$field['columnName']]['label'], $data); - $data = str_replace('', sprintf('label_%s_%d', $this->_profilePage['page'], $fieldIndex), $data); - $data = str_replace('', $this->_table[$field['columnName']]['content'], $data); - $data = str_replace('', sprintf('content_%s_%d', $this->_profilePage['page'], $fieldIndex), $data); - $data = str_replace('', sprintf('row_%s_%d', $this->_profilePage['page'], $fieldIndex), $data); - - echo $data; - } - - echo $sectionBottomContent . $pageBottomContent; - - ?> - - _currentColumn = $columnName; - } - ob_start(); - } - - public function endColumnLabel() - { - $this->_table[$this->_currentColumn]['label'] = ob_get_contents(); - ob_end_clean(); - } - - public function startColumnContent($columnName = false) - { - if ($columnName !== false) - { - $this->_currentColumn = $columnName; - } - ob_start(); - } - - public function endColumnContent() - { - echo ''; - - $this->_table[$this->_currentColumn]['content'] = ob_get_contents(); - ob_end_clean(); - } -} diff --git a/lib/Encryption.php b/lib/Encryption.php deleted file mode 100755 index 799996ae8..000000000 --- a/lib/Encryption.php +++ /dev/null @@ -1,114 +0,0 @@ -_td = mcrypt_module_open($algorithm, '', $mode, ''); - if ($this->_td === false) - { - return false; - } - - /* Use UNIX random number generator if available. */ - if (strstr(PHP_OS, 'WIN') !== false) - { - $randomSeed = MCRYPT_RAND; - } - else - { - $randomSeed = MCRYPT_DEV_RANDOM; - } - - /* If an initialization vector was not specified, create one; - * otherwise ensure that the specified IV is the proper size. - */ - if ($iv === false) - { - $iv = mcrypt_create_iv( - mcrypt_enc_get_iv_size($this->_td), $randomSeed - ); - } - else - { - $iv = substr($iv, 0, mcrypt_enc_get_iv_size($this->_td)); - } - - /* Trim the key to the maximum allowed key size. */ - $key = substr($key, 0, mcrypt_enc_get_key_size($this->_td)); - - /* Initialize the MCrypt library. */ - mcrypt_generic_init($this->_td, $key, $iv); - } - - - public function encrypt($plainText) - { - /* Base64 encode data to protect special characters. */ - return base64_encode(mcrypt_generic($this->_td, $plainText)); - } - - public function decrypt($cypherText) - { - /* Base64-decode the encrypted data and decrypt it. */ - $plainText = mdecrypt_generic($this->_td, base64_decode($cypherText)); - - /* Remove any \0 padding. */ - return rtrim($plainText, "\0"); - } - - - public function __destruct() - { - /* Clean up after ourselves. */ - mcrypt_generic_deinit($this->_td); - mcrypt_module_close($this->_td); - } -} - -?> diff --git a/lib/JavaScriptCompressor.php b/lib/JavaScriptCompressor.php deleted file mode 100755 index d99b62767..000000000 --- a/lib/JavaScriptCompressor.php +++ /dev/null @@ -1,121 +0,0 @@ -compress($string); - } - - /** - * Compresses a string of JavaScript code, removing whitespace, extra - * newlines, and extra whitespace. - * - * @param string Uncompressed JavaScript source code. - * @return string Compressed JavaScript code. - */ - public function compressString($string) - { - return $this->compress($string); - } - - /** - * Compresses a string of JavaScript code, removing whitespace, extra - * newlines, and extra whitespace. - * - * @param string Uncompressed JavaScript source code. - * @return string Compressed JavaScript code. - */ - protected function compress($string) - { - /* Remove leading and trailing whitespace from each line (note, the - * ungreedy modifier before the '$' in the below regular expression - * should theoretically not be needed, but without it, it seems to - * eat newlines. - */ - $string = preg_replace('/^\s*(.*?)\s*?$/m', '\1', $string); - - /* Remove C / C++ comments. - * - * \x27 is a single quote, \x5c is a backslash. - * - * This is based on code from Jeffrey Friedl's Mastering Regular - * Expressions, 3rd Edition (O'Reilly Media, Inc.). - * - * If you're thinking about rewriting this, you'll probably break it. - * It's very fragile ;). - */ - $string = preg_replace( - '@([^"\x27/]+|"[^\x5c"]*(?:\x5c.[^\x5c"]*)*"[^"\x27/]*|\x27[^\x27\x5c]*(?:\x5c.[^\x27\x5c]*)*\x27[^"\x27/]*)|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|//[^\n]*@', - '\1', - $string - ); - - /* Remove any blank lines from the string. */ - $string = StringUtility::removeEmptyLines($string); - - /* "Safe" newline removal. This should work with just about any code - * that a browser's JavaScript implementation can understand. - * Significant newlines will never be removed. - */ - $string = preg_replace('/;\n/', ';', $string); - $string = preg_replace('/\{\n/', '{', $string); - $string = preg_replace('/\)\n{/', ') {', $string); - $string = preg_replace('/\}\nelse/', '} else', $string); - $string = preg_replace('/else\n\{/', 'else {', $string); - - return $string; - } -} - -?> diff --git a/lib/Profile.php b/lib/Profile.php deleted file mode 100755 index 9fb3881ff..000000000 --- a/lib/Profile.php +++ /dev/null @@ -1,1219 +0,0 @@ -_siteID = $siteID; - $this->_db = DatabaseConnection::getInstance(); - $this->_savedProfileID = $profileID; - $this->_savedProfile = false; - $this->_titleCache = false; - } - - /** - * Get the internal profile ID which is saved on the get() call. - * - * @return mixed Integer ID of the internal profile or false if there is none - */ - public function getProfileID() - { - return $this->_savedProfileID; - } - - public function getProfile() - { - if ($this->_savedProfileID !== false && $this->_savedProfile !== false) - { - return $this->_savedProfile['profile']; - } - else - { - return false; - } - } - - public function getProfileStylesheet() - { - if ($this->_savedProfileID !== false && $this->_savedProfile !== false) - { - return sprintf('./profile/%s/style.css', $this->_savedProfile['profile']); - } - else - { - return false; - } - } - - /** - * Set the internal profile ID variable. - * - * @param integer ID from the profile table - * @return mixed The new value of the internal variable - */ - public function setProfileID($profileID = false) - { - return ($this->_savedProfileID = $profileID); - } - - /** - * Load all profile titles into memory so they aren't queried one-by-one on a - * page load. - * - * @param integer ID from the profile table or false to use the internal profile id - * @return boolean true on successfully cache, false on failure - */ - public function cacheTitles($profileID = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $this->setProfileID($profileID); - $this->_titleCache = $this->getAllTitles($profileID); - - return true; - } - - /********************************************************************************************** - * - * THE FOLLOWING FUNCTIONS DEAL PRIMARILY WITH THE PROFILE TABLE - * - *********************************************************************************************/ - - /** - * Base select-area SQL from a get*() method to prevent data duplication between - * similar get() methods. - * - * @return string extendible SQL statement - */ - public function getBaseSQL() - { - $sql = - "SELECT - profile.profile_id as profileID, - profile.profile as profile, - profile.title, - profile.active as isActive, - profile.date_created as dateCreated, - profile.date_modified as dateModified"; - - return $sql; - } - - /** - * Returns an associative array describing a site-wide or user-specific profile. If a user - * has no set profile, the site profile will be returned. If there is no site profile, - * a default site profile will be created. If a default profile is unable to be created, - * boolean false is returned. - * - * @param integer profileID ID from the profile table or false to return the active profile - * @param integer userID ID from the user table or false to return site-wide profile - * @param boolean true to cache titles for faster lookup, false for faster return/no cacheing - * - * @return mixed array on success, false on failure - */ - public function get($profileID = false, $userID = false, $cacheTitles = true) - { - if ($userID !== false) - { - $critereon1 = - "RIGHT JOIN user - ON user.profile_id = profile.profile_id"; - $critereon2 = sprintf( - "AND - user.user_id = %s", - $this->_db->makeQueryInteger($userID) - ); - } - else - { - $critereon1 = - "RIGHT JOIN site - ON (site.site_id = profile.site_id AND site.profile_id = profile.profile_id)"; - $critereon2 = ''; - } - - if ($profileID !== false) - { - $profileCritereon = sprintf( - "AND - profile.profile_id = %s", - $this->_db->makeQueryInteger($profileID) - ); - } - else - { - $profileCritereon = sprintf( - "AND - profile.active = 1" - ); - } - - $sql = sprintf( - "%s - FROM - profile - %s - WHERE - profile.site_id = %d - %s - %s", - $this->getBaseSQL(), - $critereon1, - $this->_siteID, - $critereon2, - $profileCritereon - ); - - $rs = $this->_db->getAssoc($sql); - - // Provided a user_id but found no profile, try getting the site profile - if (empty($rs) && $userID !== false && $profileID === false) - { - return $this->get(false, false); - } - - // No profile exists for site or provided profile_id - if (empty($rs)) - { - // Make an empty profile and attach it to the site - $id = $this->add('Default Profile', true); - if ($id !== false) - { - $site = new Site($this->_siteID); - if ($site->setProfile($id) !== false) - { - return $this->get(false, false); - } - } - } - - // Save the profile ID to an internal variable for later use (if requested) - if (!empty($rs)) - { - $this->_savedProfileID = $rs['profileID']; - $this->_savedProfile = $rs; - - if ($cacheTitles) - { - $this->cacheTitles(); - } - - return $rs; - } - - return false; - } - - /** - * Get all profiles for a site with the users that own them (if available) - * - */ - public function getAll() - { - $sql = sprintf( - "%s - user.user_id as userID, - user.user_name as userName, - user.access_level as accessLevel, - user.first_name as firstName, - user.last_name as lastName, - user.email as email, - user.title as title - FROM - profile - LEFT JOIN - user - ON - user.profile_id = profile.profile_id - WHERE - profile.site_id = %d", - $this->getBaseSQL(), - $this->_siteID - ); - - return $this->_db->getAllAssoc($sql); - } - - /** - * Get all user and site-public profiles (not attached to other users). - * - */ - public function getAllUser($userID) - { - $sql = sprintf( - "%s - FROM - profile - WHERE - profile.site_id = %d - AND - profile.profile_id NOT IN ( - SELECT - user.profile_id - FROM - user - WHERE - user.site_id = %d - AND - user.user_id != %s - )", - $this->getBaseSQL(), - $this->_siteID, - $this->_siteID, - $this->_db->makeQueryInteger($userID) - ); - - return $this->_db->getAllAssoc($sql); - } - - /** - * Add a profile for a user or site with optional default (active). - * - * @param string Title to identify the profile - * @param boolean true for an enabled, usable profile. false to disable - */ - public function add($title, $active = true, $profile = 'Default') - { - $sql = sprintf( - "INSERT INTO - profile (site_id, title, active, date_created, date_modified, profile) - VALUES - (%d, %s, %s, NOW(), NOW(), %s)", - $this->_siteID, - $this->_db->makeQueryString($title), - $active ? '1' : '0', - $this->_db->makeQueryString($profile) - ); - - // Error handling on, primary key is auto_increment - $rs = $this->_db->query($sql); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - return false; - } - - return $this->_db->getLastInsertID(); - } - - /** - * Update a profile. - * - * @param integer ID from the profile table or false to use current ID - * @param string New title for the profile - * @param boolean Is this profile active? - * @return boolean true on success, false on failure - */ - public function update($profileID, $title, $active = true, $profile = 'Default') - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "UPDATE - profile - SET - title = %s, - active = %s, - date_modified = NOW(), - profile = %s - WHERE - profile.site_id = %s - AND - profile.profile_id = %s", - $this->_siteID, - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($profile) - ); - - $this->_db->query($sql); - return ($this->_db->getAffectedRows() > 0) ? true : false; - } - - /** - * Deletes a profile and all it's pages, titles and fields associated. - * - * @param integer ID from the profile table or false to use current ID - * @return mixed true on success, false on failure (or if profile doesn't exist) - */ - public function delete($profileID = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - // Begin transaction (if one delete fails, roll everything back, I <3 InnoDB) - $inTransaction = $this->_db->beginTransaction(); - - // Delete base profile - $sql = sprintf( - "DELETE FROM - profile - WHERE - profile_id = %s - AND - site_id = %d", - $this->_db->makeQueryInteger($profileID), - $this->_siteID - ); - - $rs = $this->_db->query($sql); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - $inTransaction && $this->_db->rollBackTransaction(); - return false; - } - else if (!$this->deletePage($profileID)) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - else if (!$this->deleteField($profileID)) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - else if (!$this->deleteTitle($profileID)) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $inTransaction && $this->_db->commitTransaction(); - - return true; - } - - - - /********************************************************************************************** - * - * THE FOLLOWING FUNCTIONS DEAL PRIMARILY WITH THE PROFILE_PAGE TABLE - * - *********************************************************************************************/ - - /** - * Get the profile for a page from the profile_page table. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Identifier for the page (i.e.: addcandidate) - * @param mixed array of the page information or false if no page exists - */ - public function getPage($profileID = false, $page) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "SELECT - profile_page.site_id as siteID, - profile_page.profile_id as profileID, - profile_page.page as page, - profile_page.columns as numColumns, - profile_page.column_width as columnWidth, - profile_page.column_height as columnHeight - FROM - profile_page - WHERE - profile_page.profile_id = %s - AND - profile_page.page = %s - AND - profile_page.site_id = %d", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_siteID - ); - - $rs = $this->_db->getAssoc($sql); - - if (empty($rs)) - { - return false; - } - else - { - return $rs; - } - } - - public function getPageFields($profileID = false, $page) - { - $sql = sprintf( - "SELECT - profile_page_field.site_id as siteID, - profile_page_field.profile_id as profileID, - profile_page_field.page, - profile_page_field.column_name as columnName, - profile_page_field.x_position as xPosition, - profile_page_field.y_position as yPosition, - profile_page_field.column_span as columnSpan, - profile_page_field.row_span as rowSpan, - profile_page_field.field_format_id as fieldFormatID - FROM - profile_page_field - WHERE - profile_page_field.profile_id = %s - AND - profile_page_field.page = %s - AND - profile_page_field.site_id = %d - ORDER BY - x_position, y_position", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_siteID - ); - - return $this->_db->getAllAssoc($sql); - } - - /** - * Adds a page to a user/site profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Identifier of the page - * @param integer Numbers of columns - * @param integer HTML-CSS width for each column - * @param integer HTML-CSS height of each column - * @return mixed ID of the inserted field or false on error - */ - public function addPage($profileID = false, $page, $numColumns, $columnWidth, $columnHeight) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "INSERT INTO - profile_page (profile_id, page, columns, column_width, column_height, site_id) - VALUES (%s, %s, %s, %s, %s, %d)", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_db->makeQueryInteger($numColumns), - $this->_db->makeQueryString($columnWidth), - $this->_db->makeQueryString($columnHeight), - $this->_siteID - ); - - // No errors, primary key violations indicate page exists - $rs = $this->_db->query($sql, true); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - return false; - } - - return true; - } - - /** - * Updates a page on a user/site profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Identifier of the page - * @param integer Numbers of columns - * @param integer Pixel width for each column - * @param integer Pixel height of each column - * @return boolean true on success, false on failure - */ - public function updatePage($profileID = false, $page, $numColumns, $columnWidth, $columnHeight) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "UPDATE - profile_page - SET - columns = %s, - width = %s, - height = %s - WHERE - profile_page.profile_id = %s - AND - profile_page.page = %s - AND - profile_page.site_id = %d", - $this->_db->makeQueryInteger($numColumns), - $this->_db->makeQueryInteger($columnWidth), - $this->_db->makeQueryInteger($columnHeight), - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_siteID - ); - - $this->_db->query($sql); - return ($this->_db->getAffectedRows() > 0) ? true : false; - } - - /** - * Delete a profile page (or all pages for a profile) - * - * @param integer ID from the profile table or false to use the current ID - * @param string Identifier for the page (boolean false to delete all pages in the profile) - * @return boolean true on success or no pages deleted, false on failure - */ - public function deletePage($profileID = false, $page = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $inTransaction = $this->_db->beginTransaction(); - - if ($page !== false) - { - $criterion = sprintf( - "AND - page = %s", - $this->_db->makeQueryString($page) - ); - } - else - { - $criterion = ''; - } - - $sql = sprintf( - "DELETE FROM - profile_page - WHERE - profile_id = %s - %s - AND - profile_page.site_id = %d", - $this->_db->makeQueryInteger($profileID), - $criterion, - $this->_siteID - ); - - $rs = $this->_db->query($sql); - if (!$rs) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - else if (!$this->deleteField($profileID)) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $inTransaction && $this->_db->commitTransaction(); - - return true; - } - - - - /********************************************************************************************** - * - * THE FOLLOWING FUNCTIONS DEAL PRIMARILY WITH THE PROFILE_PAGE_FIELD TABLE - * - *********************************************************************************************/ - - /** - * Gets profile information for a field on a page. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Identifier from the profile_page table - * @param string Name of the column from the database (i.e.: first_name) - * @return mixed Array of the field data or false if no field exists in the current profile - */ - public function getField($profileID = false, $page, $columnName) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "SELECT - profile_page_field.profile_id as profileID, - profile_page_field.page, - profile_page_field.column_name as columnName, - profile_page_field.x_position as xPosition, - profile_page_field.y_position as yPosition, - profile_page_field.column_span as columnSpan, - profile_page_field.row_span as rowSpan, - profile_page_field.field_format_id as fieldFormatID - FROM - profile_page_field - WHERE - profile_page_field.profile_id = %s - AND - profile_page_field.page = %s - AND - profile_page_field.column_name = %s - AND - profile_page_field.site_id = %d", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_db->makeQueryString($columnName), - $this->_siteID - ); - - $rs = $this->_db->getAssoc($sql); - - if (empty($rs)) - { - return false; - } - - return $rs; - } - - /** - * Enters a field into a page connected to a site/user profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Page from the profile_page table (i.e.: addcandidate) - * @param string Column from the database (i.e.: first_name) - * @param string Title for the column or boolean false to use existing text - * If you specify boolean false and no existing text exists, this function - * will fail like all who tried to defeat Chuck Norris. - * @param integer X position in the grid - * @param integer Y position in the grid - * @param integer Number of columns this field should span - * @param integer Number of rows this field should span - * @param boolean true if the field should be shown, false if hidden - */ - public function addField($profileID = false, $page, $columnName, $title = false, $xPosition = 0, - $yPosition = 0, $columnSpan = 1, $rowSpan = 1) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - // We're adding to two tables, make this transactional (fail on either) - $inTransaction = $this->_db->beginTransaction(); - - if (!$title) - { - // Add column name as the column text, failure means it's already set - $result = $this->addTitle($profileID, $columnName, $columnName, false); - } - else - { - // Try to insert title text - $result = $this->addTitle($profileID, $columnName, $title, false); - - // It's ok to fail, that means it already exists. Update it. - if (!$result) - { - // If the update fails, that means nothing was changed, so no need to check. - $this->updateTitle($profileID, $columnName, $title, false); - } - } - - $sql = sprintf( - "INSERT INTO - profile_page_field (profile_id, page, column_name, x_position, y_position, column_span, - row_span, site_id) - VALUES (%s, %s, %s, %s, %s, %s, %s, %d)", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_db->makeQueryString($columnName), - $this->_db->makeQueryInteger($xPosition), - $this->_db->makeQueryInteger($yPosition), - $this->_db->makeQueryInteger($columnSpan), - $this->_db->makeQueryInteger($rowSpan), - $this->_siteID - ); - - // No errors, primary key violations indicate field exists - $rs = $this->_db->query($sql, true); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $inTransaction && $this->_db->commitTransaction(); - return true; - } - - /** - * Updates a field in a page connected to a site/user profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Page from the profile_page table - * @param string Column from the database (i.e.: first_name) - * @param string Title Use boolean false to retain value. Setting this value will change - * ALL INSTANCES of column_name regardless of which field they're attached - * to in the profile. - * @param integer X position in the grid - * @param integer Y position in the grid - * @param integer Number of columns this field should span - * @param integer Number of rows this field should span - * @param boolean true if the field should be shown, false if hidden - */ - public function updateField($profileID = false, $page, $columnName, $title = false, - $xPosition = 0, $yPosition = 0, $columnSpan = 1, $rowSpan = 1) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - if ($title !== false) - { - // Update all occurances of this column name title - // No need to error check, false just means nothing was changed - $this->updateTitle($profileID, $columnName, $title, false); - } - - $sql = sprintf( - "UPDATE - profile_page_field - SET - x_position = %s, - y_position = %s, - column_span = %s, - row_span = %s - WHERE - profile_id = %s - AND - page = %s - AND - column_name = %s - AND - site_id = %d", - $this->_db->makeQueryInteger($xPosition), - $this->_db->makeQueryInteger($yPosition), - $this->_db->makeQueryInteger($columnSpan), - $this->_db->makeQueryInteger($rowSpan), - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($page), - $this->_db->makeQueryString($columnName), - $this->_siteID - ); - - return $this->_db->query($sql); - } - - /** - * Attempts to delete a field from a page or all fields from the profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Name of the page from the profile_page table - * @param string Column from the database - */ - public function deleteField($profileID = false, $page = false, $columnName = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $inTransaction = $this->_db->beginTransaction(); - - if ($page !== false && $columnName !== false) - { - $criterion = sprintf( - "AND - page = %s - AND - column_name = %s", - $this->_db->makeQueryString($page), - $this->_db->makeQueryString($columnName) - ); - } - else if ($page === false || $columnName === false) {} - else - { - // Cannot do a selective page/column only delete - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $sql = sprintf( - "DELETE FROM - profile_page_field - WHERE - profile_id = %s - %s - AND - site_id = %d", - $this->_db->makeQueryInteger($profileID), - $criterion, - $this->_siteID - ); - - $rs = $this->_db->query($sql); - - if (!$rs) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $inTransaction && $this->_db->commitTransaction(); - - return true; - } - - - /********************************************************************************************** - * - * THE FOLLOWING FUNCTIONS DEAL PRIMARILY WITH THE PROFILE_TITLE TABLE - * - *********************************************************************************************/ - - /** - * Template SQL for getting a row from the profile_title table so no - * rewrites between get(), getAll() etc. - * - * @return string SQL retrieval code - */ - public function getTitleBaseSQL() - { - $sql = sprintf( - "SELECT - profile_title.site_id as siteID, - profile_title.profile_id as profileID, - profile_title.column_name as columnName, - profile_title.title as title, - profile_title.note as note - FROM - profile_title - WHERE - profile_title.site_id = %d", - $this->_siteID - ); - - return $sql; - } - - /** - * Get the title for a column name for a given profile. If none is found, - * boolean false is returned. Otherwise an associate array. - * - * @param integer ID from the profile table or false to use the current ID - * @param mixed Array or boolean false - */ - public function getTitle($profileID = false, $columnName) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - // If title cacheing is enabled and we're using the internal profile ID, - // then return the value from the cache instead of running another query. - if ($this->_savedProfileID !== false && $this->_savedProfileID == $profileID && - $this->_titleCache !== false) - { - foreach ($this->_titleCache as $item) - { - if (!strcmp($item['columnName'], $columnName)) - { - return $item; - } - } - - return $columnName; - } - - $sql = sprintf( - "%s - AND - profile_title.profile_id = %s - AND - profile_title.column_name = %s", - $this->getTitleBaseSQL(), - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($columnName) - ); - - $rs = $this->_db->getAssoc($sql); - - return empty($rs) ? false : $rs; - } - - public function getTitleText($profileID = false, $columnName) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - // If title cacheing is enabled and we're using the internal profile ID, - // then return the value from the cache instead of running another query. - if ($this->_savedProfileID !== false && $this->_savedProfileID == $profileID && - $this->_titleCache !== false) - { - foreach ($this->_titleCache as $item) - { - if (!strcmp($item['columnName'], $columnName)) - { - return $item['title']; - } - } - - return $columnName; - } - - $sql = sprintf( - "SELECT - profile_title.title as title - FROM - profile_title - WHERE - profile_title.profile_id = %s - AND - profile_title.column_name = %s - AND - profile_title.site_id = %d", - $this->_siteID, - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($columnName) - ); - - $rs = $this->_db->getAssoc($sql); - if (!$rs || empty($rs) || !isset($rs['title'])) - { - // Try to add the new title text since it doesn't seem to exist - $this->addTitle($profileID, $columnName, $columnName, false); - - return $columnName; - } - - return $rs['title']; - } - - /** - * Gets all profile titles for a specific profile. - * - * @param integer ID from the profile table or false to use the current ID - * @return array Empty or populated array of titles and their values - */ - public function getAllTitles($profileID = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - // If title cacheing is enabled and we're using the internal profile ID, - // then return the value from the cache instead of running another query. - if ($this->_savedProfileID !== false && $this->_savedProfileID == $profileID && - $this->_titleCache !== false) - { - return $this->_titleCache; - } - - $sql = sprintf( - "%s - AND - profile_title.profile_id = %s", - $this->getTitleBaseSQL(), - $this->_db->makeQueryInteger($profileID) - ); - - return $this->_db->getAllAssoc($sql); - } - - /** - * Adds a title for a given column name in a profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Name of the column "first_name" - * @param string Title for the column "First Name" - * @param string Anything to describe the column in more detail than the title or boolean false for null - * @return mixed Integer ID of the insert or boolean false on failure - */ - public function addTitle($profileID = false, $columnName, $title, $note = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "INSERT INTO - profile_title (profile_id, column_name, title, note, site_id) - VALUES - (%s, %s, %s, %s, %d)", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($columnName), - $this->_db->makeQueryString($title), - $note !== false && !empty($note) ? $this->_db->makeQueryString($note) : 'NULL', - $this->_siteID - ); - - // No errors, as primary key "duplicates" errors indicate title exists - $rs = $this->_db->query($sql, true); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - return false; - } - - // If cacheing is enabled, add it the new title to the local cache - if ($this->_savedProfileID !== false && $this->_titleCache !== false) - { - $this->_titleCache[] = array( - 'profileID' => $profileID, - 'column_name' => $columnName, - 'title' => $title, - 'note' => $note !== false ? $note : '' - ); - } - - return true; - } - - /** - * Updates a title for a given column name in a profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Name of the column "first_name" - * @param string Title for the column "First Name" - * @param string Anything to describe the column in more detail than the title - * @return boolean True or false, true meaning success - */ - public function updateTitle($profileID = false, $columnName, $title, $note = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $sql = sprintf( - "UPDATE - profile_title - SET - title = %s, - note = %s - WHERE - profile_title.profile_id = %s - AND - profile_title.column_name = %s - AND - profile_title.site_id = %d", - $this->_db->makeQueryString($title), - $note !== false && !empty($note) ? $this->_db->makeQueryString($note) : 'NULL', - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($columnName), - $this->_siteID - ); - - $rs = $this->_db->query($sql); - - if (!$rs || $this->_db->getAffectedRows() <= 0) - { - return false; - } - else - { - return true; - } - } - - /** - * Delete a title from the profile_title table or all from a profile. - * - * @param integer ID from the profile table or false to use the current ID - * @param string Name of the unique column - * @return boolean true on success or none deleted, false on error - */ - public function deleteTitle($profileID = false, $columnName = false) - { - if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID))) - { - return false; - } - - $inTransaction = $this->_db->beginTransaction(); - - $sql = sprintf( - "DELETE FROM - profile_title - WHERE - profile_id = %s - AND - column_name = %s - AND - site_id = %d", - $this->_db->makeQueryInteger($profileID), - $this->_db->makeQueryString($columnName), - $this->_siteID - ); - - $rs = $this->_db->query($sql); - - if (!$rs) - { - $inTransaction && $this->_db->rollbackTransaction(); - return false; - } - - $inTransaction && $this->_db->commitTransaction(); - - return true; - } - - - /********************************************************************************************** - * - * THE FOLLOWING FUNCTIONS ARE TABLE IN-SPECIFIC/GENERAL FUNCTIONS - * - *********************************************************************************************/ - -}