public function test_save() { $test = array(Message::TYPE_FATAL => array(0 => array('title' => "Fatal error", 'body' => "there was a fatal error... somewhere")), Message::TYPE_NOTICE => array(0 => array('title' => 'test', 'body' => 'The message body'), 1 => array('title' => 'another', 'body' => "a test body", 'url' => 'http://localhost/?x=y', 'linkText' => 'go to localhost'))); $_SESSION[MessageQueue::SESSIONKEY] = $test; $q = new MessageQueue(true); $q->save(); // make sure Message::save() hasn't been called (which saves to "message" instead of "messages") $this->assertFalse(isset($_SESSION[Message::SESSIONKEY])); //fix up our test data so things are in the correct order. foreach ($test as $k => $data) { foreach ($data as $i => $msg) { $url = null; if (isset($msg['url'])) { $url = $msg['url']; } $txt = null; if (isset($msg['linkText'])) { $txt = $msg['linkText']; } $newMsg = array('title' => $msg['title'], 'body' => $msg['body'], 'url' => $url, 'type' => $k, 'linkText' => $txt); $test[$k][$i] = $newMsg; } } $this->assertEquals($test, $_SESSION[MessageQueue::SESSIONKEY], ToolBox::debug_print($_SESSION, 0)); $this->assertEquals(3, $q->getCount()); $this->assertEquals(1, $q->getCount(Message::TYPE_FATAL)); $this->assertEquals(2, $q->getCount(Message::TYPE_NOTICE)); $this->assertEquals(0, $q->getCount(Message::TYPE_ERROR)); $this->assertEquals(0, $q->getCount(Message::TYPE_STATUS)); }
public function test_update() { $x = new Character(__METHOD__, 1, $this->dbObj); $x->load($this->dbObj); $data = $x->data; $this->assertTrue(is_numeric($x->characterId)); $this->assertTrue(is_array($x->data)); $this->assertTrue(isset($data['character_name']), ToolBox::debug_print($data)); $x->update('character_name', __FUNCTION__); $this->assertNotEquals($data, $x->data); $x->load($this->dbObj); $this->assertEquals($data, $x->data); $x->update('character_name', __CLASS__); $this->assertNotEquals($data, $x->data); $this->assertTrue($x->save($this->dbObj)); $this->assertNotEquals($data, $x->load($this->dbObj)); $data['character_name'] = __CLASS__; $this->assertEquals($data, $x->data); $changes = array('speed' => 999, 'hair_color' => "GReEEN", 'size' => "Medium Large-ish", 'notes' => "MOREea STUFfl qaewrqwe \n\t"); $x->mass_update($changes); $this->assertTrue($x->save($this->dbObj)); $afterMassUpdate = $x->load($this->dbObj); foreach ($changes as $k => $v) { $this->assertEquals($v, $afterMassUpdate[$k]); } }
public function testConfig() { $this->assertFalse(defined('SITE_ROOT')); $configFile = dirname(__FILE__) . '/files/siteConfig.ini'; $this->assertTrue(file_exists($configFile)); $x = new SiteConfig($configFile, null); $this->assertTrue(is_object($x)); // $this->assertTrue(is_array($x->config)); $this->assertTrue(is_array($GLOBALS)); $myFs = new FileSystem(dirname(__FILE__)); // so... set things as constants and GLOBALS foreach ($x->get_valid_sections() as $sectionName) { $x->make_section_constants($sectionName); $x->make_section_globals($sectionName); } $this->assertEquals(ToolBox::resolve_path_with_dots(dirname($configFile) . '/..'), $GLOBALS['SITE_ROOT']); $this->assertEquals($GLOBALS['SITE_ROOT'], $GLOBALS['SITEROOT']); //Test to make sure the constant and the global are identical. $this->assertEquals(constant('SITE_ROOT'), $GLOBALS['SITE_ROOT']); $this->assertEquals('CS_SESSID', constant('SESSION_NAME')); $this->assertTrue(isset($GLOBALS['SESSION_NAME'])); $this->assertFalse(isset($GLOBALS['API_AUTHTOKEN'])); $testProjectSection = $x->get_section('cs-project'); $this->assertEquals(1, count($testProjectSection)); $a = $x->get_fullConfig(); $this->assertEquals($a['cs-project']['api_authtoken'], $a['test']['TOKEN']); $this->assertEquals($a['cs-project']['api_authtoken'], $a['test']['TOKEN2']); $keys = array_keys($a); $this->assertEquals($x->get_valid_sections(), $keys); foreach ($keys as $name) { $this->assertEquals($a[$name], $x->get_section($name)); } }
public function test_basics() { $this->assertTrue(is_dir($this->dir)); $myFile = __CLASS__ . '-test.lock'; $myTestContents = '(' . __FILE__ . ') ' . __METHOD__ . ': line #' . __LINE__ . ': This is a test... ' . microtime(true); $lf = new _test_csLockfile($this->dir, $myFile); $this->assertEquals($myFile, $lf->lockFile); $this->assertFalse(file_exists($myFile)); $lf->create_lockfile($myTestContents); $this->assertEquals($this->dir . '/' . $myFile, $lf->get_lockfile(), ToolBox::debug_print($lf, 0)); $this->assertTrue(file_exists($myFile)); $this->assertEquals(file_get_contents($myFile), $myTestContents); $this->assertEquals(file_get_contents($myFile), $lf->read_lockfile()); $this->assertNotEquals(file_get_contents($myFile), $myTestContents . ' '); $lf->delete_lockfile(); $this->assertFalse(file_exists($myFile)); $numLocks = 10; $locks = array(); for ($x = 0; $x < $numLocks; $x++) { $locks[$x] = new _test_csLockfile($this->dir, $x . '.lock'); } $this->assertEquals(count($locks), $numLocks); foreach ($locks as $i => $lock) { $this->assertFalse(file_exists($this->dir . '/' . $i . '.lock')); $this->assertTrue((bool) $lock->create_lockfile('test... ' . $i)); $this->assertEquals(basename($this->dir . '/' . $i . '.lock'), basename($lock->get_lockfile())); $this->assertTrue($lock->delete_lockfile()); $this->assertTrue((bool) strlen($lock->get_lockfile())); $this->assertFalse(file_exists($lock->get_lockfile())); } }
public function test_get_logs() { $x = new cs_webdblogger($this->dbObj, __CLASS__); // create some logs to search through. // $x->log_by_class(__METHOD__, "error"); $createRecords = array('MAIN' => array('first', 'second', 'third', 'fourth'), 'xxx' => array('fifth', 'sixth'), 'error' => array('seventh'), 'another' => array('EigTh')); $totalRecords = 0; $testRecords = array(); $byClass = array(); foreach ($createRecords as $class => $list) { foreach ($list as $details) { $id = $x->log_by_class($details, $class); $this->assertTrue(is_numeric($id)); $testRecords[$id] = $details; if (isset($byClass[$class])) { $byClass[$class]++; } else { $byClass[$class] = 1; } $totalRecords++; } } foreach (array_keys($createRecords) as $class) { $theLogs = $x->get_logs($class); $this->assertEquals(count($createRecords[$class]), count($theLogs), "Failed to find logs that match '" . $class . "'... " . ToolBox::debug_print($theLogs)); } // $data = $x->get_logs(null); // // $this->assertEquals(1, count($data), ToolBox::debug_print($data,1)); // // $this->assertEquals(1, count($x->get_logs('test'))); }
public function run_upgrade() { #$this->db->beginTrans(__METHOD__); ToolBox::debug_print(__METHOD__ . ": running SQL file..."); $this->db->run_sql_file(dirname(__FILE__) . '/schemaChangesFor_0.6.1.sql'); #$this->db->commitTrans(__METHOD__); return true; }
public function test_get_total_weight() { $x = new CharacterSheet($this->dbObj, __METHOD__, 1); $this->assertTrue(is_numeric($x->characterId), ToolBox::debug_print($x)); $this->assertEquals(0, $x->get_total_weight(false)); $this->assertEquals($x->get_total_weight(true), $x->get_total_weight(false)); //now create some gear. $manualWeight = 0; $itemList = array(); $createThis = array(array('torches', 1, 10), array('lead nuggets', 10, 10), array('misc', 4, 200)); $g = new Gear(); $g->characterId = $x->characterId; foreach ($createThis as $data) { $manualWeight += round($data[1] * $data[2], 1); $xData = array('character_id' => $x->characterId, 'gear_name' => $data[0], 'weight' => $data[1], 'quantity' => $data[2]); $id = $g->create($this->dbObj, $xData); $itemList[$id] = $xData; } $this->assertEquals($manualWeight, Gear::calculate_list_weight($itemList)); //now, at first, this should be 0 because we haven't re-loaded the sheet. $this->assertEquals(0, $x->get_total_weight(false)); $this->assertEquals(0, $x->get_total_weight(true)); $x->load(); $this->assertEquals($manualWeight, $x->get_total_weight(false)); $this->assertEquals($manualWeight, $x->get_total_weight(true)); $withWeapons = $manualWeight; $w = new Weapon(); $w->characterId = $x->characterId; $wpns = array('great_sword' => 5, 'long_sword' => 2, 'short_sword' => 1); foreach ($wpns as $name => $wgt) { $xData = array('character_id' => $x->characterId, 'weapon_name' => $name, 'weight' => $wgt); $id = $w->create($this->dbObj, $xData); $itemList[$id] = $xData; $withWeapons += $wgt; } $x->load(); $this->assertNotEquals($manualWeight, $withWeapons); $this->assertTrue($withWeapons > $manualWeight); $this->assertEquals($manualWeight, $x->get_total_weight(false)); $this->assertEquals($x->get_total_weight(), $x->get_total_weight(false)); $this->assertEquals($withWeapons, $x->get_total_weight(true)); $withArmor = $withWeapons; $a = new Armor(); $rmr = array('big' => 10, 'small' => 1); foreach ($rmr as $name => $wgt) { $xData = array('character_id' => $x->characterId, 'armor_name' => $name, 'weight' => $wgt); $id = $a->create($this->dbObj, $xData); $itemList[$id] = $xData; $withArmor += $wgt; } $x->load(); $this->assertNotEquals($manualWeight, $withArmor); $this->assertTrue($withArmor > $withWeapons); $this->assertEquals($manualWeight, $x->get_total_weight(false)); $this->assertEquals($x->get_total_weight(), $x->get_total_weight(false)); $this->assertEquals($withArmor, $x->get_total_weight(true)); }
public static function _get_record_extras(array $recordData) { if (isset($recordData['ability_score'])) { $recordData['ability_mod'] = Ability::calculate_ability_modifier($recordData['ability_score']); } $recordData['skill_mod'] = self::calculate_skill_modifier($recordData); $recordData['is_class_skill_checked'] = ToolBox::interpret_bool($recordData['is_class_skill'], array('', 'checked="checked"')); $recordData['is_checked_checkbox'] = ToolBox::interpret_bool($recordData['is_class_skill'], array("", "checked")); return $recordData; }
/** * @codeCoverageIgnore */ public function check_requirements() { // TODO: make *sure* to stop if there's a lockfile from cs_webdbupgrade. $retval = false; if ($this->lock->is_lockfile_present()) { $retval = true; } else { ToolBox::debug_print(__METHOD__ . ": lockfile missing (" . $this->lock->get_lockfile() . ") while attempting to run test '" . $this->getLabel() . "'"); } return $retval; }
function debug_backtrace($printItForMe = NULL, $removeHR = NULL) { if (is_null($printItForMe)) { if (defined('DEBUGPRINTOPT')) { $printItForMe = constant('DEBUGPRINTOPT'); } elseif (isset($GLOBALS['DEBUGPRINTOPT'])) { $printItForMe = $GLOBALS['DEBUGPRINTOPT']; } } if (is_null($removeHR)) { if (defined('DEBUGREMOVEHR')) { $removeHR = constant('DEBUGREMOVEHR'); } elseif (isset($GLOBALS['DEBUGREMOVEHR'])) { $removeHR = $GLOBALS['DEBUGREMOVEHR']; } } //create our own backtrace data. $stuff = \debug_backtrace(); if (is_array($stuff)) { $i = 0; foreach ($stuff as $num => $arr) { if ($arr['function'] !== "debug_print_backtrace") { $fromClass = ''; if (isset($arr['class']) && strlen($arr['class'])) { $fromClass = $arr['class'] . '::'; } $args = ''; foreach ($arr['args'] as $argData) { $args = ToolBox::create_list($args, ToolBox::truncate_string(ToolBox::debug_print($argData, 0, 1, false), 600), ', '); } $fileDebug = ""; if (isset($arr['file'])) { $fileDebug = " from file <u>" . $arr['file'] . "</u>, line #" . $arr['line']; } $tempArr[$num] = $fromClass . $arr['function'] . '(' . $args . ')' . $fileDebug; } } array_reverse($tempArr); $myData = null; foreach ($tempArr as $num => $func) { $myData = ToolBox::create_list($myData, "#" . $i . " " . $func, "\n"); $i++; } } else { //nothing available... $myData = $stuff; } $backTraceData = ToolBox::debug_print($myData, $printItForMe, $removeHR); return $backTraceData; }
public function run_upgrade() { // Check if there's an existing auth table... $doSecondarySql = false; $this->db->beginTrans(__METHOD__); ToolBox::debug_print(__METHOD__ . ": running SQL file..."); $this->db->run_sql_file(dirname(__FILE__) . '/schemaChangesFor_0.4.1.sql'); if ($doSecondarySql) { ToolBox::debug_print(__METHOD__ . ": running SQL file..."); $this->db->run_sql_file(dirname(__FILE__) . '/schemaChangesFor_0.4.1__existingAuthTable.sql'); } $this->db->commitTrans(__METHOD__); return true; }
public function test_create_character_defaults_and_modifier() { $x = new Save(); $y = new Ability(); $y->characterId = $this->id; $x->characterId = $this->id; $y->create_defaults($this->dbObj); $numCreated = $x->create_character_defaults($this->dbObj); $list = $x->get_all($this->dbObj, $x->characterId); $this->assertEquals($numCreated, count($list), ToolBox::debug_print($list)); foreach ($list as $k => $data) { $data = $x->_get_record_extras($data); $this->assertEquals($data['total'], $x->calculate_total_save_modifier($data)); } }
public function test_create_and_get_all() { $x = new Weapon(); $x->characterId = $this->char->characterId; $createdWeapons = array(); $inUse = array(); $notInUse = array(); $testData = array(array('weapon_name' => 'Magic Sword +1', 'total_attack_bonus' => 6, 'damage' => '2d6+9', 'critical' => '20x3', 'range' => 30, 'special' => __METHOD__ . " gives a +1 bonus to geek", 'ammunition' => 10, 'weight' => 3, 'size' => '[HS]', 'weapon_type' => 'geek', 'in_use' => false), array('weapon_name' => 'Test #2...', 'in_use' => true)); foreach ($testData as $cData) { $cData['character_id'] = $x->characterId; $id = $x->create($this->dbObj, $cData); $this->assertTrue(is_numeric($id)); $this->assertTrue($id > 0); $data = $x->load($this->dbObj); $this->assertTrue(is_array($data)); $this->assertTrue(count($data) >= count($cData)); $this->assertFalse(isset($createdWeapons[$id])); $createdWeapons[$id] = $data; if ($cData['in_use']) { $inUse[$id] = $data; } else { $notInUse[$id] = $data; } } $allWeapons = $x->get_all($this->dbObj, $x->characterId); $this->assertTrue(is_array($allWeapons)); $this->assertEquals(count($testData), count($allWeapons), ToolBox::debug_print($allWeapons)); $this->assertTrue(isset($allWeapons[$id])); $this->assertTrue(is_array($allWeapons[$id])); $this->assertEquals($data, $allWeapons[$id]); $testUsedWpns = $x->get_all($this->dbObj, $x->characterId, true); $testNotUsedWpns = $x->get_all($this->dbObj, $x->characterId, false); $this->assertNotEquals($testNotUsedWpns, $testUsedWpns); foreach ($testUsedWpns as $id => $data) { $this->assertTrue(isset($createdWeapons[$id])); $this->assertEquals($createdWeapons[$id], $data); } foreach ($testNotUsedWpns as $id => $data) { $this->assertTrue(isset($createdWeapons[$id])); $this->assertEquals($createdWeapons[$id], $data); } }
/** * * @param bool/optional $onlyInUse If specified, returns only those with the * given value in the "in_use" column. * * @return type * @throws ErrorException */ public static function get_all(Database $dbObj, $characterId, $onlyInUse = null) { $sql = 'SELECT * FROM ' . self::tableName . ' WHERE '; //'character_id=:id'; $params = array('character_id' => $characterId); if (!is_null($onlyInUse) && is_bool($onlyInUse)) { $params['in_use'] = ToolBox::interpret_bool($onlyInUse, array('f', 't')); } $addThis = ""; foreach (array_keys($params) as $n) { $addThis = ToolBox::create_list($addThis, $n . '=:' . $n, ' AND '); } $sql .= $addThis; try { $dbObj->run_query($sql, $params); $retval = $dbObj->farray_fieldnames(self::pkeyField); } catch (Exception $e) { throw new ErrorException(__METHOD__ . ":: failed to retrieve character weapons, DETAILS::: " . $e->getMessage()); } return $retval; }
public function test_create() { $x = new Armor(); $x->characterId = $this->id; $data = array('character_id' => $this->id, 'armor_name' => __METHOD__ . " +5 of holy awesomeness", 'armor_type' => "light", 'ac_bonus' => 5, 'check_penalty' => 0, 'max_dex' => 9, 'special' => "Smells like good code", 'weight' => 12, 'max_speed' => 30, 'is_worn' => 'f'); $id = $x->create($this->dbObj, $data); $this->assertTrue(is_numeric($id)); $dbData = $x->load($this->dbObj); //make sure we understand how "interpret_bool()" works.. $this->assertFalse(ToolBox::interpret_bool('f', array(false, true))); $this->assertTrue(ToolBox::interpret_bool('t', array(false, true))); $this->assertTrue(is_array($dbData)); $this->assertTrue(count($dbData) > 0); foreach ($data as $f => $v) { if ($f == 'is_worn') { $expected = ToolBox::interpret_bool($v, array(false, true)); $this->assertEquals($expected, $dbData[$f], "field (" . $f . ") value doesn't match... expected (" . $expected . "), got (" . $dbData[$f] . ")"); } else { $this->assertEquals($v, $dbData[$f]); } } }
/** * Turns out there's no real good way to view the parsed data without * evaluating GLOBALS and constants. Ick. */ public function testConfig() { $this->assertFalse(defined('SITE_ROOT')); $configFile = dirname(__FILE__) . '/files/siteConfig.xml'; $this->assertTrue(file_exists($configFile)); $x = new cs_siteConfig($configFile, null); $this->assertTrue(is_object($x)); $this->assertTrue(is_array($x->config)); foreach ($x->get_valid_sections() as $section) { $x->make_section_constants($section); $x->make_section_globals($section); } $this->assertTrue(is_array($GLOBALS)); $this->assertEquals(ToolBox::resolve_path_with_dots(dirname($configFile) . '/..'), $GLOBALS['SITE_ROOT']); $this->assertEquals($GLOBALS['SITE_ROOT'], $GLOBALS['SITEROOT']); //BUG!!!! see https://github.com/crazedsanity/cs-webapplibs/issues/26 $this->assertEquals(constant('SITE_ROOT'), $GLOBALS['SITE_ROOT']); $this->assertEquals('CS_SESSID', constant('SESSION_NAME')); $this->assertTrue(!empty($GLOBALS['SESSION_NAME'])); $this->assertEquals(constant('session_db_host'), constant('DB_PG_HOST')); $this->assertEquals(constant('cs_webupgradedb-RWDIR'), constant('CS_RWDIR')); $this->assertFalse(isset($GLOBALS['API_AUTHTOKEN'])); $this->assertFalse(defined('API_AUTHTOKEN')); }
public function move_file($filename, $destination) { $retval = FALSE; if ($this->is_readable($filename)) { if ($this->check_chroot($destination)) { //do the move. $filename = $this->filename2absolute($filename); $destination = $this->filename2absolute($destination); $retval = rename($filename, $destination); } else { ToolBox::debug_print(__METHOD__ . ":: " . $this->check_chroot($destination), 1); throw new exception(__METHOD__ . ':: destination is not in the directory path (from=[' . $filename . '], to=[' . $destination . ']'); } } return $retval; }
public function test_inheritance() { $_main = new Template(__DIR__ . '/files/templates/inheritance_main.tmpl'); $_sub = new Template(__DIR__ . '/files/templates/inheritance_sub.tmpl'); $mainVars = array('inheritance' => "Loads of money", 'separate' => "ONLY FOR MAIN"); $recordSet = array(0 => array('separate' => 'first'), 1 => array('separate' => 'second'), 2 => array('separate' => 'third')); $rows = $_sub->renderRows($recordSet); $_main->addVarList($mainVars); $_main->addVar('subTemplate', $rows, false); $rendered = $_main->render(false); $this->assertEquals(0, count(Template::getTemplateVarDefinitions($rendered))); $this->assertEquals(1, preg_match('/first||/', $rendered)); $this->assertEquals(1, preg_match('/second||/', $rendered)); $this->assertEquals(1, preg_match('/third||/', $rendered)); $matches = array(); $this->assertEquals(4, preg_match_all('/Loads of money/', $rendered, $matches), "inheritance failed: " . ToolBox::debug_print($matches, 0)); $this->assertEquals(4, count($matches[0]), "inheritance failed, not all variables were filled in: " . ToolBox::debug_print($matches) . "\n\n" . ToolBox::debug_print($rendered)); }
/** * @param bool $stripUndefinedVars Removes undefined template vars * @return mixed|string Rendered template */ public function render($stripUndefinedVars = false) { $numLoops = 0; if (is_string($this->_contents) || is_numeric($this->_contents)) { $out = $this->_contents; } else { $out = ""; } $rendered = array(); foreach ($this->_templates as $name => $contents) { $rendered[$name] = $contents; } $tags = array(); while (preg_match_all('~\\{' . self::VARIABLE_REGEX . '\\}~U', $out, $tags) && $numLoops < $this->recursionDepth) { $out = ToolBox::mini_parser($out, $rendered, '{', '}'); $numLoops++; } if ($stripUndefinedVars === true) { $out = preg_replace('/\\{' . self::VARIABLE_REGEX . '\\}/', '', $out); } return $out; }
/** * @expectedException InvalidArgumentException */ public function test_resolvePathException() { ToolBox::resolve_path_with_dots(NULL); }
public function test_get_all() { $x = new AuthToken($this->dbObj); //TODO: test offset/limit $this->assertEquals(array(), $x->get_all()); $x->create_token(__METHOD__, __METHOD__, null, null, 0, 0, 0); $x->create_token(__METHOD__, __METHOD__, null, null, 0, 1, 0); $x->create_token(__METHOD__, __METHOD__, null, null, 0, 1, 1); $firstData = $x->get_all(0); $firstKeys = array_keys($firstData); $this->assertEquals(2, count($firstData)); //NOTE: if this fails, the ordering has probably changed. $this->assertEquals(0, $firstData[$firstKeys[1]]['uid']); $this->assertEquals(0, $firstData[$firstKeys[1]]['token_type_id'], ToolBox::debug_print($firstData)); $secondData = $x->get_all(1); $secondKeys = array_keys($secondData); $this->assertEquals(1, count($secondData)); $this->assertEquals(1, $secondData[$secondKeys[0]]['uid']); $this->assertEquals(1, $secondData[$secondKeys[0]]['token_type_id']); $this->assertEquals(3, count($x->get_all())); $this->assertEquals(2, count($x->get_all(null, 1))); $this->assertEquals(1, count($x->get_all(null, 0))); }
public function test_basics() { $this->assertTrue(is_object($this->dbObj), "No database objects to test"); $type = 'pgsql'; $this->assertEquals($type, $this->dbObj->get_dbType(), "Database type mismatch, expecting (" . $type . "), got (" . $this->dbObj->get_dbType() . ")"); $this->assertTrue($this->reset_db(dirname(__FILE__) . '/../setup/schema.' . $type . '.sql'), "Failed to reset database"); $this->assertFalse($this->dbObj->get_transaction_status(), "Already in transaction...?"); $beginTransRes = $this->dbObj->beginTrans(); $transactionStatus = $this->dbObj->get_transaction_status(); $this->assertTrue($transactionStatus); $this->assertTrue($beginTransRes, "Start of transaction failed (" . $beginTransRes . "), status=(" . $transactionStatus . ")"); $this->dbObj->exec('CREATE TABLE test (id serial not null PRIMARY KEY, data text not null);'); $this->assertTrue($this->dbObj->get_transaction_status(), "Got out of transaction...?"); // Make sure we get 0 rows before any data has been inserted. $numRows = $this->dbObj->run_query("SELECT * FROM test"); $data = $this->dbObj->farray_fieldnames(); $this->assertEquals($numRows, count($data), "Invalid number of rows returned: expected (" . count($data) . "), got (" . $numRows . ")"); $this->assertEquals($numRows, 0, "Returned unexpected number of rows on fresh table (" . $numRows . ")"); $testData = array(0 => 'test1', 1 => 'test2'); $i = 1; $insertTestSql = "INSERT INTO test (data) VALUES (:val)"; foreach ($testData as $val) { $createdId = $this->dbObj->run_insert($insertTestSql, array('val' => $val), 'test_id_seq'); $this->assertTrue(is_numeric($createdId), "Insert did not yield integer value (" . $createdId . ")"); $this->assertEquals($i, $createdId, "Expected Id (" . $i . ") does not match created id (" . $createdId . ") for test data (" . $val . ")"); $i++; } // now make sure we've got the date expected. $numRows = $this->dbObj->run_query("SELECT * FROM test"); $data = $this->dbObj->farray_fieldnames(); $this->assertTrue(is_array($data), "Returned data in an invalid format"); $this->assertEquals($numRows, count($testData), "Invalid number of records created, expected (" . count($testData) . "), got (" . $numRows . ")"); $this->assertTrue(isset($data[0]), "Zeroth index does not exist?"); $this->assertTrue(isset($data[0]['id']), "ID index missing from returned data"); $this->assertTrue(isset($data[0]['data']), "DATA index missing from returned data"); $this->assertEquals($data[0]['id'], 1, "Invalid ID in element 0, expected 1 but got (" . $data[0]['id'] . ")"); $this->assertEquals($data[1]['id'], 2, "Invalid ID in element 1, expected 2 but got (" . $data[1]['id'] . ")"); $numRows = $this->dbObj->run_query("SELECT * FROM test"); $data = $this->dbObj->farray_nvp('id', 'data'); $this->assertEquals("test1", $data[1], "Expected ID 1 to be 'test1', but instead got '" . $data[1] . "'"); $this->assertEquals("test2", $data[2], "Expected ID 2 to be 'test2', but instead got '" . $data[2] . "'"); // add a record with a specified ID (retrieving the sequence value will appear to be incorrect, because we're not using it). $testData[4] = "test5"; $createdId = $this->dbObj->run_insert("INSERT INTO test (id, data) VALUES (:id, :val)", array('id' => 5, 'val' => $testData[4]), 'test_id_seq'); $this->assertNotEquals($createdId, 5, "Inserting out-of-order index failed, insert ID should have been 2 (not " . $createdId . ")"); $numRows = $this->dbObj->run_query("SELECT * FROM test"); $data = $this->dbObj->farray_nvp('id', 'data'); $this->assertTrue(is_array($data), "Did not retrieve array of information from database... (" . ToolBox::debug_var_dump($data, 0) . ")"); $this->assertEquals(count($data), count($testData), "Number of records in database (" . count($data) . ") do not match what is expected (" . count($testData) . ")"); $testData[2] = "test3"; $createdId = $this->dbObj->run_insert($insertTestSql, array('val' => $testData[2]), 'test_id_seq'); $this->assertEquals($createdId, 3, "Failed to insert ID #3...?"); $testData[3] = "test4"; $createdId = $this->dbObj->run_insert($insertTestSql, array('val' => $testData[3]), 'test_id_seq'); $this->assertEquals($createdId, 4, "Failed to insert ID #4...?"); // Make sure farray_fieldnames works as expected. $numRows = $this->dbObj->run_query("SELECT * FROM test"); $data = $this->dbObj->farray_fieldnames('id'); $this->assertEquals(array('id' => 1, 'data' => 'test1'), $data[1]); $this->assertEquals(array('id' => 2, 'data' => 'test2'), $data[2]); $this->assertEquals(array('id' => 3, 'data' => 'test3'), $data[3]); $this->assertEquals(array('id' => 4, 'data' => 'test4'), $data[4]); $this->assertEquals(array('id' => 5, 'data' => 'test5'), $data[5]); $this->assertEquals(count($data), 5); $this->assertTrue($this->dbObj->commitTrans()); $this->assertTrue($this->dbObj->beginTrans()); //Okay, here's where there should be an error (re-inserting data that's already there) try { $createdId = $this->dbObj->run_insert($insertTestSql, array('val' => $testData[4]), 'test_id_seq'); $this->assertTrue(false, "DANGER WILL ROBINSON! This should have produced an error!"); } catch (Exception $ex) { // Make sure it said something about a duplicate key, throw an error if not. $this->assertEquals(1, preg_match('~duplicate key~', $ex->getMessage()), "Error was strange: " . $ex->getMessage()); } $this->assertTrue($this->dbObj->commitTrans()); // make sure we're not in a transaction. $this->assertFalse($this->dbObj->get_transaction_status()); // Simpler test for farray() $numRows = $this->dbObj->run_query("SELECT * FROM test WHERE id > :id ORDER BY id", array('id' => 0)); $data = $this->dbObj->farray(); $this->assertTrue($numRows == count($data)); $this->assertTrue($numRows > 0); $this->assertTrue($numRows == 5); $this->assertEquals($data[0][0], 1); $this->assertEquals($data[0][1], 'test1'); $this->assertEquals($data[0]['id'], 1); $this->assertEquals($data[0]['data'], 'test1'); $testElement4 = array(0 => 5, 'id' => 5, 1 => 'test5', 'data' => 'test5'); $this->assertEquals($data[4], $testElement4); // use farray_nvp(), but swap id with value (should work, since values are unique) $numRows = $this->dbObj->run_query("SELECT * FROM test WHERE id > :id ORDER BY :orderBy", array('id' => 0, 'orderBy' => 'id')); $data = $this->dbObj->farray_nvp('data', 'id'); $this->assertEquals($numRows, count($data)); $this->assertEquals($numRows, 5); $this->assertEquals($data['test5'], 5); $this->assertEquals($data['test3'], 3); $numRows = $this->dbObj->run_query("SELECT * FROM test WHERE id=:id", array('id' => 2)); $data = $this->dbObj->get_single_record(); $this->assertEquals(array('id' => 2, 'data' => 'test2'), $data); }
function send_activation_email($infoArr) { //setup the variables for sending the email... $to = $infoArr['email']; $subj = "New Account Activation [" . $infoArr['uid'] . "]"; //read-in the contents of the email template. $page = new cs_genericPage(false, "content/registrationEmail.tmpl"); //parse the template... foreach ($infoArr as $tmpl => $value) { $page->add_template_var($tmpl, $value); } #$body = mini_parser($tmpl, $infoArr, "{", "}"); $body = $page->return_printed_page(); $result = $this->send_single_email($to, $subj, $body); $this->debug[__METHOD__] = $result; $this->logger->log_by_class(ToolBox::debug_print($this->debug, 0), 'debug'); return $result; }
public function create_sql_insert_string(array $data) { #$retval = ""; if (is_array($data) && count($data)) { $fields = ""; $values = ""; foreach ($data as $k => $v) { $fields = ToolBox::create_list($fields, $k, ", "); $values = ToolBox::create_list($values, ':' . $k, ", "); } if (strlen($fields) && strlen($values)) { $retval = ' (' . $fields . ') VALUES (' . $values . ')'; } else { throw new Exception(__METHOD__ . ": no fields (" . $fields . ") or values (" . $values . ") created... " . $this->gfObj->debug_print($data, 0)); } } else { throw new Exception(__METHOD__ . ": unable to create insert string, no fields given"); } return $retval; }
public function update() { $updateSql = ""; $params = $this->_clean_data_array($this->_data); foreach ($params as $k => $v) { if (count($this->booleanFields) && in_array($k, $this->booleanFields)) { $params[$k] = ToolBox::interpret_bool($v, array('f', 't')); } $updateSql = ToolBox::create_list($updateSql, $k . '=:' . $k, ','); } $sql = "UPDATE " . $this->_dbTable . " SET " . $updateSql . " WHERE " . $this->_dbPkey . "=:id"; $params['id'] = $this->id; try { $this->dbObj->run_update($sql, $params); $retval = true; } catch (Exception $ex) { throw new LogicException(__METHOD__ . ": unable to update table '" . $this->_dbTable . "', DETAILS::: " . $ex->getMessage()); } return $retval; }
public function test_create() { $x = new Skill(); $x->characterId = $this->char->characterId; $a = new Ability(); $a->characterId = $this->char->characterId; $a->create_defaults($this->dbObj); $cache = $a->get_all($this->dbObj, $this->char->id); $createdSkills = array(); $this->assertEquals(6, count($cache)); $this->assertTrue(is_array($this->autoSkills)); $this->assertTrue(count($this->autoSkills) > 10); foreach ($this->autoSkills as $id => $theData) { $name = $theData[0]; $attribute = $theData[1]; $this->assertTrue(isset($cache[$attribute]), "missing attribute '" . $attribute . "' in cache... " . ToolBox::debug_print($cache, 0)); $this->assertTrue(isset($cache[$attribute]['ability_id'])); $insertData = array('character_id' => $x->characterId, 'ability_id' => $cache[$attribute]['ability_id'], 'skill_name' => $name); $id = $x->create($this->dbObj, $insertData); $this->assertTrue(is_numeric($id)); $this->assertTrue($id > 0); $testData = $x->load($this->dbObj); $this->assertTrue(is_array($testData)); $this->assertTrue(count($testData) > 0); foreach ($insertData as $k => $v) { $this->assertEquals($v, $testData[$k]); } $this->assertFalse(isset($createdSkills[$id])); $createdSkills[$id] = $testData; } }
/** * * @param $uid (int/optional) Find tokens just for this uid * @param $type (int/optional) Find tokens just of this type * @param $limit (int/optional) Limit number of results (pagination) * @param $offset (int/optional) Offset number of results (pagination) * * @return type * @throws Exception */ public function get_all($uid = null, $type = null, $limit = null, $offset = 0) { $sql = "SELECT *, (a.max_uses - a.total_uses) AS remaining_uses, \n\t\t\t(NOW() - a.expiration) AS time_remaining FROM cswal_auth_token_table \n\t\t\tAS a INNER JOIN cswal_token_type_table AS t USING (token_type_id)"; $params = array(); if (!is_null($uid)) { $params['uid'] = $uid; } if (!is_null($type)) { $params['token_type_id'] = $type; } if (count($params) > 0) { $criteria = ""; foreach ($params as $field => $val) { $criteria = ToolBox::create_list($criteria, $field . '=:' . $field, " AND "); } $sql .= " WHERE " . $criteria; } $sql .= " ORDER BY t.token_type, t.token_desc"; if (!is_null($limit) && is_numeric($limit)) { $sql .= " LIMIT " . $limit; } if (!is_null($offset) && is_numeric($offset)) { $sql .= " OFFSET " . $offset; } try { $numrows = $this->db->run_query($sql, $params); $retval = array(); if ($numrows > 0) { $retval = $this->db->farray_fieldnames('auth_token_id'); } } catch (Exception $ex) { throw new Exception(__METHOD__ . ": failed to retrieve tokens, SQL::: " . $sql . "\n\nDETAILS::: " . $ex->getMessage()); } return $retval; }
public function test_interpret_bool() { $this->assertEquals(true, ToolBox::interpret_bool('1')); $this->assertEquals(true, ToolBox::interpret_bool('1', array(false, true))); $this->assertEquals(true, ToolBox::interpret_bool('1', array('0' => false, '1' => true))); $this->assertEquals(false, ToolBox::interpret_bool('1', array(true, false))); }
public function create_ability_select(cs_genericPage $page, $skillId = null, $selectThis = null) { $abilityList = Ability::get_all_abilities($this->dbObj, true); $abilityOptionList = ToolBox::array_as_option_list($abilityList, $selectThis); if (is_null($skillId)) { $skillId = 'new'; } $optionListRepArr = array('skills__selectAbility__extra' => '', 'skill_id' => $skillId, 'optionList' => $abilityOptionList); if (is_numeric($skillId)) { } else { $optionListRepArr['skills__selectAbility__extra'] = 'class="newRecord"'; $optionListRepArr['skillNum'] = 'new'; $optionListRepArr['skill_id'] = 'new'; } $retval = ToolBox::mini_parser($page->templateRows['skills__selectAbility'], $optionListRepArr, '%%', '%%'); return $retval; }
public function test_get_user_data() { $x = new cs_authUser($this->dbObj); $data = $x->get_user_data('test', $x::STATUS_ENABLED); $this->assertTrue(is_array($data), ToolBox::debug_print($data)); $this->assertTrue(isset($data['uid'])); $this->assertTrue(isset($data['username'])); $this->assertTrue(isset($data['passwd'])); // $this->assertTrue(isset($data['date_created'])); // $this->assertTrue(isset($data['last_login'])); // $this->assertTrue(isset($data['email'])); $this->assertTrue(isset($data['user_status_id'])); try { $this->assertFalse(is_array($x->get_user_data('test', $x::STATUS_DISABLED))); } catch (Exception $ex) { if (!preg_match('/failed to retrieve a single user \\(0\\)/', $ex->getMessage())) { $this->fail("unexpected or invalid exception message: " . $ex->getMessage()); } } try { $this->assertFalse(is_array($x->get_user_data('test', $x::STATUS_PENDING))); } catch (Exception $ex) { if (!preg_match('/failed to retrieve a single user \\(0\\)/', $ex->getMessage())) { $this->fail("unexpected or invalid exception message: " . $ex->getMessage()); } } try { $this->assertFalse(is_array($x->get_user_data('test', 99999))); } catch (Exception $ex) { if (!preg_match('/failed to retrieve a single user \\(0\\)/', $ex->getMessage())) { $this->fail("unexpected or invalid exception message: " . $ex->getMessage()); } } }