/** * Helper function to workaround old WP versions * @param integer $testId * @param array $termIds * @return array */ public function sortTermIdsByTermOrder($testId, $termIds) { if (empty($testId) || empty($termIds)) { return $termIds; } /* @var $db fDatabase */ $db = fORMDatabase::retrieve(__CLASS__, 'read'); $records = $db->translatedQuery(' SELECT tt.term_id FROM ' . WP_DB_PREFIX . 'term_relationships tr JOIN ' . WP_DB_PREFIX . 'term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_id IN (' . implode(', ', array_map('intval', $termIds)) . ') AND tr.object_id = ' . intval($testId) . ' ORDER BY tr.term_order '); $result = array(); foreach ($records as $record) { $result[] = $record['term_id']; } return $result; }
public static function setUpBeforeClass() { if (defined('SKIPPING')) { return; } $db = new fDatabase(DB_TYPE, DB, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT); if (DB_TYPE == 'sqlite') { $db->execute(file_get_contents(DB_SETUP_FILE)); $db->execute(file_get_contents(DB_EXTENDED_SETUP_FILE)); } $db->execute(file_get_contents(DB_POPULATE_FILE)); $db->execute(file_get_contents(DB_EXTENDED_POPULATE_FILE)); self::$db = $db; self::$schema = new fSchema($db); fORMDatabase::attach(self::$db); fORMSchema::attach(self::$schema); fORMOrdering::configureOrderingColumn('TopAlbum', 'position'); fORMOrdering::configureOrderingColumn('FavoriteAlbum', 'position'); fORMOrdering::configureOrderingColumn('YearFavoriteAlbum', 'position'); if (defined('MAP_TABLES')) { fORM::mapClassToTable('User', 'user'); fORM::mapClassToTable('Group', 'group'); fORM::mapClassToTable('Artist', 'popular_artists'); fORM::mapClassToTable('Album', 'records'); } }
public function importUsers() { try { $raw = fRequest::get('content'); $this->db = fORMDatabase::retrieve(); $this->db->query('BEGIN'); foreach (explode("\n", $raw) as $i) { $j = preg_split('/\\s+/', $i); if (count($j) < 2) { continue; } $x = $j[0]; $y = $j[1]; $user = new Name(); $user->setRealname($x); $user->setStudentNumber($y); $user->store(); } $this->db->query('COMMIT'); $this->ajaxReturn(array('result' => 'success')); } catch (fException $e) { if (isset($this->db)) { $this->db->query('ROLLBACK'); } $this->ajaxReturn(array('result' => 'failure', 'message' => $e->getMessage())); } }
public static function getImage($id_entity, $id_section) { $result = fORMDatabase::retrieve()->unbufferedQuery("SELECT * FROM resource WHERE id_entity='{$id_entity}' AND id_section='{$id_section}' AND resource_type='i' LIMIT 1"); foreach ($result as $r) { return $r['url']; } }
public static function hasAccepted($problem) { if (self::$accepted_cache === NULL) { $db = fORMDatabase::retrieve(); $result = $db->translatedQuery('SELECT DISTINCT problem_id FROM records WHERE owner=%s AND verdict=%i', fAuthorization::getUserToken(), Verdict::AC); $result->unescape(array('problem_id' => 'integer')); self::$accepted_cache = array(); foreach ($result as $row) { self::$accepted_cache[] = $row['problem_id']; } } return in_array($problem->getId(), self::$accepted_cache); }
public function setUp() { if (defined('SKIPPING')) { $this->markTestSkipped(); } fORMDatabase::attach(self::$db); fORMSchema::attach(self::$schema); if (defined('MAP_TABLES')) { fORM::mapClassToTable('User', 'user'); fORM::mapClassToTable('Group', 'group'); fORM::mapClassToTable('Artist', 'popular_artists'); fORM::mapClassToTable('Album', 'records'); } }
public function update($id) { try { $this->db = fORMDatabase::retrieve(); $this->db->query('BEGIN'); $profile = new Profile($id); if (UserHelper::getProfileId() != $profile->getId() and !UserHelper::isEditor()) { throw new fValidationException('not allowed'); } $profile->setStartYear(fRequest::get('start_year')); $profile->setClassNumber(fRequest::get('class_number')); $profile->setStudentNumber(trim(fRequest::get('student_number'))); $profile->setBirthday(trim(fRequest::get('birthday'))); $profile->setGender(fRequest::get('gender')); //$profile->setLocation(trim(fRequest::get('location'))); $province = trim(fRequest::get('province')); $city = trim(fRequest::get('city')); $profile->setLocation(self::formatLocation($province, $city)); $profile->setPostNumber(trim(fRequest::get('post_number'))); $profile->setPrivacyControl(trim(fRequest::get('privacy', 'int', 0))); $profile->setField(trim(fRequest::get('field'))); $profile->setInstitute(trim(fRequest::get('institute'))); $profile->setPosition(trim(fRequest::get('position'))); $profile->setMajor(trim(fRequest::get('major'))); $profile->setMentor(trim(fRequest::get('mentor'))); $profile->setSubscription(trim(fRequest::get('subscription'))); $profile->store(); foreach ($profile->getContacts() as $contact) { $contact->delete(); } foreach ($this->contact_types as $type) { if (strlen(trim(fRequest::get($type)))) { $contact = new Contact(); $contact->setProfileId($profile->getId()); $contact->setType($type); $contact->setContent(trim(fRequest::get($type))); $contact->setCreatedAt(Util::currentTime()); $contact->store(); } } $this->db->query('COMMIT'); Activity::fireUpdateProfile(); $this->ajaxReturn(array('result' => 'success', 'profile_id' => $profile->getId())); } catch (fException $e) { if (isset($this->db)) { $this->db->query('ROLLBACK'); } $this->ajaxReturn(array('result' => 'failure', 'message' => $e->getMessage())); } }
public function setUp() { if (defined('SKIPPING')) { $this->markTestSkipped(); } fORMDatabase::attach(self::$db); fORMDatabase::attach(self::$db2, 'db2'); fORMSchema::attach(self::$schema); fORMSchema::attach(self::$schema2, 'db2'); fORM::mapClassToTable('Db2User', 'users'); fORM::mapClassToDatabase('Db2User', 'db2'); fORM::mapClassToTable('Db2Group', 'groups'); fORM::mapClassToDatabase('Db2Group', 'db2'); }
public function setUp() { if (defined('SKIPPING')) { $this->markTestSkipped(); } fORMDatabase::attach($this->sharedFixture['db']); fORMDatabase::attach($this->sharedFixture['db2'], 'db2'); fORMSchema::attach($this->sharedFixture['schema']); fORMSchema::attach($this->sharedFixture['schema2'], 'db2'); fORM::mapClassToTable('Db2User', 'users'); fORM::mapClassToDatabase('Db2User', 'db2'); fORM::mapClassToTable('Db2Group', 'groups'); fORM::mapClassToDatabase('Db2Group', 'db2'); }
private static function ensureCountCaches() { $db = fORMDatabase::retrieve(); if (self::$accept_count_cache === NULL) { $result = $db->translatedQuery('SELECT problem_id, COUNT(1) AS count FROM records WHERE verdict=%i GROUP BY problem_id', Verdict::AC); $result->unescape(array('problem_id' => 'integer', 'count' => 'integer')); static::populateCountCache(self::$accept_count_cache, $result); } if (self::$submit_count_cache === NULL) { $result = $db->translatedQuery('SELECT problem_id, COUNT(1) AS count FROM records GROUP BY problem_id'); $result->unescape(array('problem_id' => 'integer', 'count' => 'integer')); static::populateCountCache(self::$submit_count_cache, $result); } }
protected function setUp() { if (defined('SKIPPING')) { return; } $db = new fDatabase(DB_TYPE, DB, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT); $db->execute(file_get_contents(DB_SETUP_FILE)); $db2 = new fDatabase(DB_TYPE, DB_2, DB_2_USERNAME, DB_2_PASSWORD, DB_2_HOST, DB_2_PORT); $db2->execute(file_get_contents(DB_2_SETUP_FILE)); $this->sharedFixture = array($db, $db2); fORMDatabase::attach($db); fORMDatabase::attach($db2, 'db2'); fORM::mapClassToTable('Db2User', 'users'); fORM::mapClassToDatabase('Db2User', 'db2'); fORM::mapClassToTable('Db2Group', 'groups'); fORM::mapClassToDatabase('Db2Group', 'db2'); }
public static function setUpBeforeClass() { if (defined('SKIPPING')) { return; } $db = new fDatabase(DB_TYPE, DB, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT); $db->execute(file_get_contents(DB_SETUP_FILE)); $db2 = new fDatabase(DB_TYPE, DB_2, DB_2_USERNAME, DB_2_PASSWORD, DB_2_HOST, DB_2_PORT); $db2->execute(file_get_contents(DB_2_SETUP_FILE)); self::$db = $db; self::$db2 = $db2; fORMDatabase::attach($db); fORMDatabase::attach($db2, 'db2'); fORM::mapClassToTable('Db2User', 'users'); fORM::mapClassToDatabase('Db2User', 'db2'); fORM::mapClassToTable('Db2Group', 'groups'); fORM::mapClassToDatabase('Db2Group', 'db2'); }
public function setUp() { if (defined('SKIPPING')) { $this->markTestSkipped(); } $db = $this->sharedFixture['db']; $db->execute(file_get_contents(DB_EXTENDED_SETUP_FILE)); $db->clearCache(); fORMDatabase::attach($db); fORMSchema::attach($this->sharedFixture['schema']); fORMOrdering::configureOrderingColumn('TopAlbum', 'position'); fORMOrdering::configureOrderingColumn('FavoriteAlbum', 'position'); fORMOrdering::configureOrderingColumn('YearFavoriteAlbum', 'position'); if (defined('MAP_TABLES')) { fORM::mapClassToTable('User', 'user'); fORM::mapClassToTable('Group', 'group'); fORM::mapClassToTable('Artist', 'popular_artists'); fORM::mapClassToTable('Album', 'records'); } }
/** * Stores a record in the database, whether existing or new * * This method will start database and filesystem transactions if they have * not already been started. * * @throws fValidationException When ::validate() throws an exception * * @param boolean $force_cascade When storing related records, this will force deleting child records even if they have their own children in a relationship with an RESTRICT or NO ACTION for the ON DELETE clause * @return fActiveRecord The record object, to allow for method chaining */ public function store($force_cascade = FALSE) { $class = get_class($this); if (fORM::getActiveRecordMethod($class, 'store')) { return $this->__call('store', array()); } fORM::callHookCallbacks($this, 'pre::store()', $this->values, $this->old_values, $this->related_records, $this->cache); $db = fORMDatabase::retrieve($class, 'write'); $schema = fORMSchema::retrieve($class); try { $table = fORM::tablize($class); // New auto-incrementing records require lots of special stuff, so we'll detect them here $new_autoincrementing_record = FALSE; if (!$this->exists()) { $pk_columns = $schema->getKeys($table, 'primary'); $pk_column = $pk_columns[0]; $pk_auto_incrementing = $schema->getColumnInfo($table, $pk_column, 'auto_increment'); if (sizeof($pk_columns) == 1 && $pk_auto_incrementing && !$this->values[$pk_column]) { $new_autoincrementing_record = TRUE; } } $inside_db_transaction = $db->isInsideTransaction(); if (!$inside_db_transaction) { $db->translatedQuery('BEGIN'); } fORM::callHookCallbacks($this, 'post-begin::store()', $this->values, $this->old_values, $this->related_records, $this->cache); $this->validate(); fORM::callHookCallbacks($this, 'post-validate::store()', $this->values, $this->old_values, $this->related_records, $this->cache); // Storing main table if (!$this->exists()) { $params = $this->constructInsertParams(); } else { $params = $this->constructUpdateParams(); } $result = call_user_func_array($db->translatedQuery, $params); // If there is an auto-incrementing primary key, grab the value from the database if ($new_autoincrementing_record) { $this->set($pk_column, $result->getAutoIncrementedValue()); } // Fix cascade updated columns for in-memory objects to prevent issues when saving $one_to_one_relationships = $schema->getRelationships($table, 'one-to-one'); $one_to_many_relationships = $schema->getRelationships($table, 'one-to-many'); $relationships = array_merge($one_to_one_relationships, $one_to_many_relationships); foreach ($relationships as $relationship) { $type = in_array($relationship, $one_to_one_relationships) ? 'one-to-one' : 'one-to-many'; $route = fORMSchema::getRouteNameFromRelationship($type, $relationship); $related_table = $relationship['related_table']; $related_class = fORM::classize($related_table); $related_class = fORM::getRelatedClass($class, $related_class); if ($relationship['on_update'] != 'cascade') { continue; } $column = $relationship['column']; if (!fActiveRecord::changed($this->values, $this->old_values, $column)) { continue; } if (!isset($this->related_records[$related_table][$route]['record_set'])) { continue; } $record_set = $this->related_records[$related_table][$route]['record_set']; $related_column = $relationship['related_column']; $old_value = fActiveRecord::retrieveOld($this->old_values, $column); $value = $this->values[$column]; if ($old_value === NULL) { continue; } foreach ($record_set as $record) { if (isset($record->old_values[$related_column])) { foreach (array_keys($record->old_values[$related_column]) as $key) { if ($record->old_values[$related_column][$key] === $old_value) { $record->old_values[$related_column][$key] = $value; } } } if ($record->values[$related_column] === $old_value) { $record->values[$related_column] = $value; } } } // Storing *-to-many and one-to-one relationships fORMRelated::store($class, $this->values, $this->related_records, $force_cascade); fORM::callHookCallbacks($this, 'pre-commit::store()', $this->values, $this->old_values, $this->related_records, $this->cache); if (!$inside_db_transaction) { $db->translatedQuery('COMMIT'); } fORM::callHookCallbacks($this, 'post-commit::store()', $this->values, $this->old_values, $this->related_records, $this->cache); } catch (fException $e) { if (!$inside_db_transaction) { $db->translatedQuery('ROLLBACK'); } fORM::callHookCallbacks($this, 'post-rollback::store()', $this->values, $this->old_values, $this->related_records, $this->cache); if ($new_autoincrementing_record && self::hasOld($this->old_values, $pk_column)) { $this->values[$pk_column] = self::retrieveOld($this->old_values, $pk_column); unset($this->old_values[$pk_column]); } throw $e; } fORM::callHookCallbacks($this, 'post::store()', $this->values, $this->old_values, $this->related_records, $this->cache); $was_new = !$this->exists(); // If we got here we succefully stored, so update old values to make exists() work foreach ($this->values as $column => $value) { $this->old_values[$column] = array($value); } // If the object was just inserted into the database, save it to the identity map if ($was_new) { $hash = self::hash($this->values, $class); if (!isset(self::$identity_map[$class])) { self::$identity_map[$class] = array(); } self::$identity_map[$class][$hash] = $this; } return $this; }
public function testPrecountOneToManyMultiColumn() { $set = fRecordSet::build('User'); $set->precountFavoriteAlbums(); ob_start(); fORMDatabase::retrieve()->enableDebugging(TRUE); foreach ($set as $user) { $count = $user->countFavoriteAlbums(); switch ($user->getUserId()) { case 1: $expected_count = 5; break; case 2: $expected_count = 1; break; case 3: $expected_count = 0; break; case 4: $expected_count = 0; break; } $this->assertEquals($expected_count, $count); } fORMDatabase::retrieve()->enableDebugging(FALSE); $output = ob_get_clean(); $this->assertEquals('', $output); }
/** * Associates a set of many-to-many related records with the current record * * @internal * * @param string $class The class the relationship is being stored for * @param array &$values The current values for the main record being stored * @param array $relationship The information about the relationship between this object and the records in the record set * @param array $related_info An array containing the keys `'record_set'`, `'count'`, `'primary_keys'` and `'associate'` * @return void */ public static function storeManyToMany($class, &$values, $relationship, $related_info) { $db = fORMDatabase::retrieve($class, 'write'); $schema = fORMSchema::retrieve($class); $column_value = $values[$relationship['column']]; // First, we remove all existing relationships between the two tables $join_table = $relationship['join_table']; $join_column = $relationship['join_column']; $params = array("DELETE FROM %r WHERE " . fORMDatabase::makeCondition($schema, $join_table, $join_column, '=', $column_value), $join_table, $join_column, $column_value); call_user_func_array($db->translatedQuery, $params); // Then we add back the ones in the record set $join_related_column = $relationship['join_related_column']; $related_pk_columns = $schema->getKeys($relationship['related_table'], 'primary'); $related_column_values = array(); // If the related column is the primary key, we can just use the primary keys if we have them if ($related_pk_columns[0] == $relationship['related_column'] && $related_info['primary_keys']) { $related_column_values = $related_info['primary_keys']; // Otherwise we need to pull the related values out of the record set } else { // If there is no record set, build it from the primary keys if (!$related_info['record_set']) { $related_class = fORM::classize($relationship['related_table']); $related_class = fORM::getRelatedClass($class, $related_class); $related_info['record_set'] = fRecordSet::build($related_class, array($related_pk_columns[0] . '=' => $related_info['primary_keys'])); } $get_related_method_name = 'get' . fGrammar::camelize($relationship['related_column'], TRUE); foreach ($related_info['record_set'] as $record) { $related_column_values[] = $record->{$get_related_method_name}(); } } // Ensure we aren't storing duplicates $related_column_values = array_unique($related_column_values); $join_column_placeholder = $schema->getColumnInfo($join_table, $join_column, 'placeholder'); $related_column_placeholder = $schema->getColumnInfo($join_table, $join_related_column, 'placeholder'); foreach ($related_column_values as $related_column_value) { $params = array("INSERT INTO %r (%r, %r) VALUES (" . $join_column_placeholder . ", " . $related_column_placeholder . ")", $join_table, $join_column, $join_related_column, $column_value, $related_column_value); call_user_func_array($db->translatedQuery, $params); } }
/** * Counts the related records for all records in this set in one DB query * * @param string $related_class This should be the name of a related class * @param string $route This should be a column name or a join table name and is only required when there are multiple routes to a related table. If there are multiple routes and this is not specified, an fProgrammerException will be thrown. * @return fRecordSet The record set object, to allow for method chaining */ private function precount($related_class, $route = NULL) { if (!$this->records) { return $this; } $this->validateSingleClass('precount'); // If there are no primary keys we can just exit if (!array_merge($this->getPrimaryKeys())) { return $this; } fActiveRecord::validateClass($related_class); fActiveRecord::forceConfigure($related_class); $db = fORMDatabase::retrieve($this->class, 'read'); $schema = fORMSchema::retrieve($this->class); $related_table = fORM::tablize($related_class); $table = fORM::tablize($this->class); $route = fORMSchema::getRouteName($schema, $table, $related_table, $route, '*-to-many'); $relationship = fORMSchema::getRoute($schema, $table, $related_table, $route, '*-to-many'); // Build the query out $table_and_column = $table . '.' . $relationship['column']; if (isset($relationship['join_table'])) { $table_to_join = $relationship['join_table']; $column_to_join = $relationship['join_table'] . '.' . $relationship['join_column']; } else { $table_to_join = $related_table; $column_to_join = $related_table . '.' . $relationship['related_column']; } $params = array($db->escape("SELECT count(*) AS flourish__count, %r AS flourish__column FROM %r INNER JOIN %r ON %r = %r WHERE ", $table_and_column, $table, $table_to_join, $table_and_column, $column_to_join)); $params = $this->addWhereParams($db, $schema, $params); $params[0] .= $db->escape(' GROUP BY %r', $table_and_column); // Run the query and inject the results into the records $result = call_user_func_array($db->translatedQuery, $params); $counts = array(); foreach ($result as $row) { $counts[$row['flourish__column']] = (int) $row['flourish__count']; } unset($result); $total_records = sizeof($this->records); $get_method = 'get' . fGrammar::camelize($relationship['column'], TRUE); $tally_method = 'tally' . fGrammar::pluralize($related_class); for ($i = 0; $i < $total_records; $i++) { $record = $this->records[$i]; $count = isset($counts[$record->{$get_method}()]) ? $counts[$record->{$get_method}()] : 0; $record->{$tally_method}($count, $route); } return $this; }
public function setUp() { if (defined('SKIPPING')) { $this->markTestSkipped(); } fORMDatabase::attach($this->sharedFixture['db']); fORMSchema::attach($this->sharedFixture['schema']); fORM::mapClassToTable('Flourish2User', fix_schema('flourish2.users')); fORM::mapClassToTable('Flourish2Group', fix_schema('flourish2.groups')); fORM::mapClassToTable('Flourish2Artist', fix_schema('flourish2.artists')); fORM::mapClassToTable('Flourish2Album', fix_schema('flourish2.albums')); }
/** * Validates values against unique constraints * * @param fSchema $schema The schema object for the object * @param fActiveRecord $object The instance of the class to check * @param array &$values The values to check * @param array &$old_values The old values for the record * @return array An aray of error messages for the unique constraints */ private static function checkUniqueConstraints($schema, $object, &$values, &$old_values) { $class = get_class($object); $table = fORM::tablize($class); $db = fORMDatabase::retrieve($class, 'read'); $key_info = $schema->getKeys($table); $pk_columns = $key_info['primary']; $unique_keys = $key_info['unique']; $messages = array(); foreach ($unique_keys as $unique_columns) { settype($unique_columns, 'array'); // NULL values are unique $found_not_null = FALSE; foreach ($unique_columns as $unique_column) { if ($values[$unique_column] !== NULL) { $found_not_null = TRUE; } } if (!$found_not_null) { continue; } $params = array("SELECT %r FROM %r WHERE ", $key_info['primary'], $table); $column_info = $schema->getColumnInfo($table); $conditions = array(); foreach ($unique_columns as $unique_column) { $value = $values[$unique_column]; // This makes sure the query performs the way an insert will if ($value === NULL && $column_info[$unique_column]['not_null'] && $column_info[$unique_column]['default'] !== NULL) { $value = $column_info[$unique_column]['default']; } if (self::isCaseInsensitive($class, $unique_column) && self::stringlike($value)) { $condition = fORMDatabase::makeCondition($schema, $table, $unique_column, '=', $value); $conditions[] = str_replace('%r', 'LOWER(%r)', $condition); $params[] = $table . '.' . $unique_column; $params[] = fUTF8::lower($value); } else { $conditions[] = fORMDatabase::makeCondition($schema, $table, $unique_column, '=', $value); $params[] = $table . '.' . $unique_column; $params[] = $value; } } $params[0] .= join(' AND ', $conditions); if ($object->exists()) { foreach ($pk_columns as $pk_column) { $value = fActiveRecord::retrieveOld($old_values, $pk_column, $values[$pk_column]); $params[0] .= ' AND ' . fORMDatabase::makeCondition($schema, $table, $pk_column, '<>', $value); $params[] = $table . '.' . $pk_column; $params[] = $value; } } try { $result = call_user_func_array($db->translatedQuery, $params); $result->tossIfNoRows(); // If an exception was not throw, we have existing values $column_names = array(); foreach ($unique_columns as $unique_column) { $column_names[] = fORM::getColumnName($class, $unique_column); } if (sizeof($column_names) == 1) { $messages[join('', $unique_columns)] = self::compose('%sThe value specified must be unique, however it already exists', fValidationException::formatField(join('', $column_names))); } else { $messages[join(',', $unique_columns)] = self::compose('%sThe values specified must be a unique combination, however the specified combination already exists', fValidationException::formatField(join(', ', $column_names))); } } catch (fNoRowsException $e) { } } return $messages; }
/** * Makes sure the ordering value is sane, removes error messages about missing values * * @internal * * @param fActiveRecord $object The fActiveRecord instance * @param array &$values The current values * @param array &$old_values The old values * @param array &$related_records Any records related to this record * @param array &$cache The cache array for the record * @param array &$validation_messages An array of ordered validation messages * @return void */ public static function validate($object, &$values, &$old_values, &$related_records, &$cache, &$validation_messages) { $class = get_class($object); $table = fORM::tablize($class); $db = fORMDatabase::retrieve($class, 'read'); $schema = fORMSchema::retrieve($class); foreach (self::$ordering_columns[$class] as $column => $other_columns) { $current_value = $values[$column]; $old_value = fActiveRecord::retrieveOld($old_values, $column); $params = array("SELECT MAX(%r) FROM %r", $column, $table); if ($other_columns) { $params[0] .= " WHERE "; $params = self::addOtherFieldsWhereParams($schema, $params, $table, $other_columns, $values); } $current_max_value = (int) call_user_func_array($db->translatedQuery, $params)->fetchScalar(); $new_max_value = $current_max_value; if ($new_set = self::isInNewSet($column, $other_columns, $values, $old_values)) { $new_max_value = $current_max_value + 1; $new_set_new_value = fActiveRecord::changed($values, $old_values, $column); } $column_name = fORM::getColumnName($class, $column); // Remove any previous validation warnings $filtered_messages = array(); foreach ($validation_messages as $validation_column => $validation_message) { if (!preg_match('#(^|,)' . preg_quote($column, '#') . '(,|$)#D', $validation_column)) { $filtered_messages[$validation_column] = $validation_message; } } $validation_messages = $filtered_messages; // If we have a completely empty value, we don't need to validate since a valid value will be generated if ($current_value === '' || $current_value === NULL) { continue; } if (!is_numeric($current_value) || strlen((int) $current_value) != strlen($current_value)) { $validation_messages[$column] = self::compose('%sPlease enter an integer', fValidationException::formatField($column_name)); } elseif ($current_value < 1) { $validation_messages[$column] = self::compose('%sThe value can not be less than 1', fValidationException::formatField($column_name)); } } }
<?php ob_start(); require_once 'config.php'; require_once 'user.php'; require_once 'transaction.php'; require_once 'card.php'; $db = new fDatabase('sqlite', dirname(__FILE__) . '/../var/database.db'); fORMDatabase::attach($db); fSession::setLength('30 minutes', '1 week'); fSession::setPath(dirname(__FILE__) . '/../var/session'); if ($uid = fSession::get('user')) { $user = new User($uid); } else { $user = null; }
/** * Build scales and setup their ranges from test's questions * * @return WpTesting_Model_Scale[] */ public function buildScalesWithRange() { $scales = $this->buildScales(); if (!$scales->count()) { return $scales; } $questionIds = array_filter($this->listWpTesting_Model_Questions()); if (empty($questionIds)) { return $scales; } $lastColumnInRow = $this->isMultipleAnswers() ? 's.answer_id' : 'question_id'; /* @var $db fDatabase */ $db = fORMDatabase::retrieve('WpTesting_Model_Score', 'read'); $scoresTable = fORM::tablize('WpTesting_Model_Score'); $answersTable = fORM::tablize('WpTesting_Model_Answer'); $result = $db->translatedQuery(' SELECT scale_id, SUM(minimum_in_row) AS minimum_in_column, SUM(maximum_in_row) AS maximum_in_column, SUM(sum_in_row) AS sum_in_column FROM ( SELECT scale_id, MIN(IF(score_value > 0, 0, score_value)) AS minimum_in_row, MAX(IF(score_value > 0, score_value, 0)) AS maximum_in_row, SUM(score_value) AS sum_in_row FROM ' . $scoresTable . ' AS s JOIN ' . $answersTable . ' AS a ON s.answer_id = a.answer_id WHERE TRUE AND question_id IN (' . implode(',', $questionIds) . ') AND scale_id IN (' . implode(',', $scales->getPrimaryKeys()) . ') GROUP BY scale_id, question_id, ' . $lastColumnInRow . ' HAVING minimum_in_row < maximum_in_row ) AS groupped GROUP BY scale_id '); $resultByPk = array(); foreach ($result->fetchAllRows() as $row) { $resultByPk[$row['scale_id']] = $row; } foreach ($scales as $scale) { if (isset($resultByPk[$scale->getId()])) { $values = $resultByPk[$scale->getId()]; $scale->setRange($values['minimum_in_column'], $values['maximum_in_column'], $values['sum_in_column']); } } return $scales; }
protected function __construct() { $this->modelName = str_replace('_Query_', '_Model_', get_class($this)); $this->tableName = fORM::tablize($this->modelName); $this->db = fORMDatabase::retrieve($this->modelName, 'read'); }
/** * Return the instance of the fSchema class * * @param string $class The class the object will be used with * @return fSchema The schema instance */ public static function retrieve($class = 'fActiveRecord') { if (substr($class, 0, 5) == 'name:') { $database_name = substr($class, 5); } else { $database_name = fORM::getDatabaseName($class); } if (!isset(self::$schema_objects[$database_name])) { self::$schema_objects[$database_name] = new fSchema(fORMDatabase::retrieve($class)); } return self::$schema_objects[$database_name]; }
public function testPrecountOneToMany() { $set = fRecordSet::build('Flourish2Artist'); $set->precountFlourish2Albums(); ob_start(); fORMDatabase::retrieve()->enableDebugging(TRUE); foreach ($set as $artist) { $count = $artist->countFlourish2Albums(); switch ($artist->getArtistId()) { case 1: $expected_count = 3; break; case 2: $expected_count = 2; break; case 3: $expected_count = 1; break; } $this->assertEquals($expected_count, $count); } fORMDatabase::retrieve()->enableDebugging(FALSE); $output = ob_get_clean(); $this->assertEquals('', $output); }
//Set the Template root, and set the header and footer $tmpl = new fTemplating($root_path . '/views/'); $tmpl->enableMinification('development', dirname(__FILE__) . '/../js_cache/',dirname(__FILE__) . '/..'); $tmpl->add('css','/bootstrap/bootstrap.min.css'); $tmpl->add('css','/assets/css/jquery-ui.css'); $tmpl->add('js','/assets/js/jquery.min.js'); $tmpl->add('js','/assets/js/jquery-ui.min.js'); $tmpl->add('js','/assets/js/jquery.collapsible.js'); $tmpl->add('js','/assets/js/jquery.graphite.js'); $tmpl->add('js','/bootstrap/js/bootstrap-modal.js'); $tmpl->add('js','/bootstrap/js/bootstrap-twipsy.js'); $tmpl->add('js','/bootstrap/js/bootstrap-popover.js'); $tmpl->set('header', 'header.php'); $tmpl->set('footer', 'footer.php'); //Set DB connection (using flourish it isn't actually connected to until the first use) $mysql_db = new fDatabase('mysql', $database_name, $database_user, $database_password); //Connect the db to the ORM functions fORMDatabase::attach($mysql_db); //Start the Flourish Session fSession::open();
<?php fSession::open(); $idUser = fSession::get(SESSION_ID_USER); if (empty($idUser) || !fAuthorization::checkACL('news', 'delete')) { header('Location: ' . SITE); exit("No se ha podido acceder a esta secci&oacite;n"); } $id = fRequest::encode('id', 'string'); if (strstr($id, ",")) { fORMDatabase::retrieve()->query("DELETE FROM economic_units WHERE economic_unit_id IN ({$id})"); } else { $author = new EconomicUnit($id); $author->delete(); } fORMDatabase::retrieve()->query("DELETE FROM economic_units_has_economic_unit_categories WHERE economic_units_economic_unit_id IN ({$id})");
/** * Makes sure the ordering value is sane, removes error messages about missing values * * @internal * * @param fActiveRecord $object The fActiveRecord instance * @param array &$values The current values * @param array &$old_values The old values * @param array &$related_records Any records related to this record * @param array &$cache The cache array for the record * @param array &$validation_messages An array of ordered validation messages * @return void */ public static function validate($object, &$values, &$old_values, &$related_records, &$cache, &$validation_messages) { $class = get_class($object); $table = fORM::tablize($class); $column = self::$ordering_columns[$class]['column']; $other_columns = self::$ordering_columns[$class]['other_columns']; $current_value = $values[$column]; $old_value = fActiveRecord::retrieveOld($old_values, $column); $sql = "SELECT max(" . $column . ") FROM " . $table; if ($other_columns) { $sql .= " WHERE " . self::createOtherFieldsWhereClause($table, $other_columns, $values); } $current_max_value = (int) fORMDatabase::retrieve()->translatedQuery($sql)->fetchScalar(); $new_max_value = $current_max_value; if ($new_set = self::isInNewSet($column, $other_columns, $values, $old_values)) { $new_max_value = $current_max_value + 1; $new_set_new_value = fActiveRecord::changed($values, $old_values, $column); } $column_name = fORM::getColumnName($class, $column); // Remove any previous validation warnings $filtered_messages = array(); foreach ($validation_messages as $validation_message) { if (!preg_match('#^' . str_replace('___', '(.*?)', preg_quote(fValidationException::formatField('___' . $column_name . '___'), '#')) . '#', $validation_message)) { $filtered_messages[] = $validation_message; } } $validation_messages = $filtered_messages; // If we have a completely empty value, we don't need to validate since a valid value will be generated if ($current_value === '' || $current_value === NULL) { return; } if (!is_numeric($current_value) || strlen((int) $current_value) != strlen($current_value)) { $validation_messages[] = self::compose('%sPlease enter an integer', fValidationException::formatField($column_name)); } elseif ($current_value < 1) { $validation_messages[] = self::compose('%sThe value can not be less than 1', fValidationException::formatField($column_name)); } }
$fileName[] = $_FILES['files']['name'][$i]; $fileType[] = $_FILES['files']['type'][$i]; copy($dir . $fileName[$i], $dir2 . $fileName[$i]); $image3 = new fImage($dir2 . $fileName[$i]); $image3->cropToRatio(1, 1, 'left', 'bottom'); $image3->resize(200, 0); $image3->saveChanges(); /* $ftp = new ftp($user,$pass); $ftp->upload($dir . "/" . $fileName[$i], 'DIR EN REMOTE'); # resize $ftp->upload($dir2 . "/" . $fileName[$i], 'DIR EN REMOTE'); $image->delete */ } /* * Add Files to DataBase (Resource) */ try { $statement = fORMDatabase::retrieve()->prepare("INSERT INTO resource (id_entity,id_section,token,url,resource_type,description) VALUES (%i, 1, '', %s, %s, %s)"); for ($i = 0; $i < $uploaded; $i++) { if ($imageDescrip[$i] == "Si es necesario escribe la descripción del archivo") { $imageDescrip[$i] = ""; } fORMDatabase::retrieve()->query($statement, $lastId, $fileName[$i], $banner->getResourceType($fileType[$i]), $imageDescrip[$i]); } } catch (fSQLException $e) { die("No se ha podido ejecutar la consulta"); } } exit("1");
/** * Enables caching on the fDatabase, fSQLTranslation and fSchema objects used for the ORM * * This method will cache database schema information to the three objects * that use it during normal ORM operation: fDatabase, fSQLTranslation and * fSchema. To allow for schema changes without having to manually clear * the cache, all cached information will be cleared if any * fUnexpectedException objects are thrown. * * This method should be called right after fORMDatabase::attach(). * * @param fCache $cache The object to cache schema information to * @param string $database_name The database to enable caching for * @param string $key_token This is a token that is used in cache keys to prevent conflicts for server-wide caches - when non-NULL the document root is used * @return void */ public static function enableSchemaCaching($cache, $database_name = 'default', $key_token = NULL) { if ($key_token === NULL) { $key_token = $_SERVER['DOCUMENT_ROOT']; } $token = 'fORM::' . $database_name . '::' . $key_token . '::'; $db = fORMDatabase::retrieve('name:' . $database_name); $db->enableCaching($cache, $token); fException::registerCallback($db->clearCache, 'fUnexpectedException'); $sql_translation = $db->getSQLTranslation(); $sql_translation->enableCaching($cache, $token); $schema = fORMSchema::retrieve('name:' . $database_name); $schema->enableCaching($cache, $token); fException::registerCallback($schema->clearCache, 'fUnexpectedException'); }