/** * Tests whether we can grab an Episode that is due to be released within a * specified length of time from now. */ public function testGetOneEpisodeReleasedWithinSeconds() { // Create Test Subreddit $subreddit = new Subreddit(); $subreddit->setName(rand(0, 1000)); $subreddit->setDomain(rand(0, 1000)); $subreddit->save(); // Create Test Episode $episode = new Episode(); $episode->setReleaseDate(date('Y-m-d H:i:s', time() + 100)); $episode->setSubreddit($subreddit); $episode->save(); $another_episode = new Episode(); $another_episode->setReleaseDate(date('Y-m-d H:i:s', time() + 500)); $another_episode->setSubreddit($subreddit); $another_episode->save(); $seconds_within = 200; // Run table query to grab episode without ID $random_episode = EpisodeTable::getInstance()->getOneEpisodeReleasedWithinSeconds($seconds_within); $this->assertTrue($random_episode instanceof Episode); // Run table query to grab episode WITH ID $random_episode = EpisodeTable::getInstance()->getOneEpisodeReleasedWithinSeconds($seconds_within, $episode->getIncremented()); $this->assertTrue($random_episode instanceof Episode); // Run table query to grab anotherepisode WITH ID $random_episode = EpisodeTable::getInstance()->getOneEpisodeReleasedWithinSeconds($seconds_within, $another_episode->getIncremented()); $this->assertFalse($random_episode instanceof Episode); // Delete episodes $another_episode->delete(); $episode->delete(); // Delete subreddit. $subreddit->delete(); }
/** * Tests saving a sfGuardUserSubredditMembership that identifies a User as * "blocked" for a particular Subreddit. When this occurs, all existing * future EpisodeAssignments should be deleted because blocked users cannot * participate with the Subreddit. */ public function testSavingBlockedUser() { // Establish fake Subreddit $subreddit = new Subreddit(); $subreddit->setName(rand(0, 1000)); $subreddit->setDomain(rand(0, 1000)); $subreddit->save(); // Establish User $user = new sfGuardUser(); $user->setEmailAddress(rand(0, 100000)); $user->setUsername(rand(0, 10000)); $user->setIsValidated(1); $user->save(); $user_id = $user->getIncremented(); $this->assertNotEquals(0, $user_id); // Establish Episode for Subreddit $episode = new Episode(); $episode->setSubreddit($subreddit); $episode->setReleaseDate(date('Y-m-d H:i:s', time() + 34000)); $episode->save(); $author_type = AuthorTypeTable::getInstance()->findOneBy('type', 'squid'); $deadline = new Deadline(); $deadline->setSubreddit($subreddit); $deadline->setAuthorType($author_type); $deadline->setSeconds(0); $deadline->save(); $episode_assignment = new EpisodeAssignment(); $episode_assignment->setSfGuardUser($user); $episode_assignment->setEpisode($episode); $episode_assignment->setAuthorType($author_type); $episode_assignment->save(); $number_of_episodes = EpisodeAssignmentTable::getInstance()->createQuery()->select('COUNT(EpisodeAssignment.id)')->leftJoin('Episode')->where('subreddit_id = ?', $subreddit->getIncremented())->andWhere('EpisodeAssignment.sf_guard_user_id = ?', $user_id)->andWhere('Episode.release_date > NOW()')->groupBy('EpisodeAssignment.id')->count(); $this->assertEquals(1, $number_of_episodes); // Establish User Membership as Blocked $blocked = MembershipTable::getInstance()->findOneBy('type', 'blocked'); $user_membership = new sfGuardUserSubredditMembership(); $user_membership->setSubreddit($subreddit); $user_membership->setSfGuardUser($user); $user_membership->setMembership($blocked); // Save Membership $user_membership->save(); // Asert that User has zero Episodes $number_of_episodes = EpisodeAssignmentTable::getInstance()->createQuery()->select('COUNT(EpisodeAssignment.id)')->leftJoin('Episode')->where('subreddit_id = ?', $subreddit->getIncremented())->andWhere('EpisodeAssignment.sf_guard_user_id = ?', $user_id)->andWhere('Episode.release_date > NOW()')->groupBy('EpisodeAssignment.id'); $sql = $number_of_episodes->getSqlQuery(); $number_of_episodes = $number_of_episodes->count(); $this->assertTrue(0 == $number_of_episodes, $sql . "\n" . $subreddit->getIncremented() . "\n" . $user_id); // Remove User Membership $user_membership->delete(); // Delete User $user->delete(); // Delete Episode $episode->delete(); // Delete Deadline $deadline->delete(); // Delete Subreddit $subreddit->delete(); }
public function find_or_create_by_post_id($post_id) { $episode = Episode::find_one_by_property('post_id', $post_id); if ($episode) { return $episode; } $episode = new Episode(); $episode->post_id = $post_id; $episode->save(); return $episode; }
public function create($args) { $p = PermissionHandler::getInstance(); // do we have an error thing? if (!$p->allowedto(PermissionHandler::PERM_CREATE_PROJECT)) { Utils::error("You don't have permission to create projects."); return; } if (isset($_POST['go'])) { // ok, if the user has selected to do automatic lookup // of the series or automatic adding of episodes, // then we need to confirm that we're looking up the right // series. // scratch that. we should confirm no matter what, but if they chose // automatic lookup, do it here. $this->vars['tid'] = 0; $this->vars['search'] = array(); if (!isset($_POST['confirm'])) { // implement automatic lookup // if the user wants automatic lookup, do it. if (isset($_POST['autolookup'])) { if ($_POST['autolookup'] == "on") { require_once dirname(__FILE__) . "/../plugins/animedata.php"; // fill in the autolookup stuff... // first we need to find the anime. $search = AnimeData::search($_POST['name']); if ($search) { if (!isset($_POST['tid'])) { $tidkey = 0; } else { foreach ($search as $key => $entry) { if ($entry[0] == $_POST['tid']) { $tidkey = $key; } } } $this->vars['tid'] = $search[$tidkey][0]; $this->vars['search'] = $search; $description = AnimeData::description($search[$tidkey][0]); if ($description) { $_POST['description'] = $description; } else { Utils::warning("Could not find description."); } $epcount = AnimeData::epcount($search[$tidkey][0]); $_POST['epsaired'] = $epcount['aired']; $_POST['epstotal'] = $epcount['total']; $_POST['airtime'] = $epcount['airtime']; } else { Utils::warning("Could not find anime."); } } } $this->vars['confirm'] = $_POST; // LOL LAZY // display a confirmation $this->view = "confirm"; return; } // if they've already confirmed, then go ahead and create the project $project = new Project(); $project->name = $_POST['name']; $project->shortname = $_POST['shortname']; $project->description = $_POST['description']; $project->episodes = $_POST['epstotal']; if ($_POST['leader'] != "none") { $project->leader = $_POST['leader']; } if ($_POST['template'] != "none") { $project->template = $_POST['template']; $template = Doctrine::getTable('Template')->find(0); } if (isset($_POST['tid'])) { $project->syoboi_id = $_POST['tid']; } $project->created = date("Y-m-d H:i:s"); $project->save(); if (isset($_POST['tid'])) { require_once dirname(__FILE__) . "/../plugins/animedata.php"; $times = AnimeData::times($_POST['tid']); } // if the user has chosen to automatically add episodes, do so now if ($_POST['autoeps'] == "aired") { $total = $_POST['epsaired']; } else { if ($_POST['autoeps'] == "total") { $total = $_POST['epstotal']; } else { $total = 0; } } for ($i = 1; $i <= $total; $i++) { $episode = new Episode(); $episode->project = $project->id; $episode->episode = $i; if (isset($times)) { $episode->airdate = strtok($times[$i][0]['airtime'], " "); } $episode->created = date("Y-m-d H:i:s"); $episode->save(); if (isset($template)) { $template->createTasks($episode->id); } } // and finally, send them to the project page. Utils::redirect("projects/display/" . $project->id); $this->view = null; return; } // otherwise, i don't think we actually need to do anything... right? // YEAH WE DO RETARD. ITS CALLED GIVE TEMPLATE SHIT. $q = Doctrine_Query::create()->select('s.id,s.nickname')->from('Staff s'); $users = $q->fetchArray(); // make this easier to use. foreach ($users as $row) { $this->vars['users'][] = array($row['id'], $row['nickname']); } $q = Doctrine_Query::create()->select('t.id, t.name')->from('Template t'); $templates = $q->fetchArray(); // make this easier to use. foreach ($templates as $row) { $this->vars['templates'][] = array($row['id'], $row['name']); } }
/** * We've combined the process for preventing saving with a specific call for * deletion to aid in handling errors and dealing with unsaved objects. * This tests whether the exception is thrown */ public function testdeleteWithException() { $subreddit = new Subreddit(); $subreddit->setName(rand(0, 10000)); $subreddit->setDomain(rand(0, 10000)); $subreddit->save(); $user = new sfGuardUser(); $user->setUsername(rand(0, 10000)); $user->setEmailAddress(rand(0, 10000)); $user->setIsValidated(1); $user->save(); $first = AuthorTypeTable::getInstance()->findOneByType('squid'); $episode = new Episode(); $episode->setReleaseDate(date('Y-m-d H:i:s', time() + 100000)); $episode->setSubreddit($subreddit); $episode->save(); $deadline = new Deadline(); $deadline->setSubreddit($subreddit); $deadline->setAuthorType($first); $deadline->setSeconds(0); $deadline->save(); $assignment = new EpisodeAssignment(); $assignment->setSfGuardUser($user); $assignment->setEpisode($episode); $assignment->setAuthorType($first); $assignment->save(); // Delete with exception $exception_thrown = false; $exception_code = 987654321; try { $assignment->deleteWithException("Test exception", $exception_code); } catch (sfException $exception) { $this->assertEquals($exception_code, $exception->getCode()); unset($exception); $exception_thrown = true; } $this->assertTrue($exception_thrown); // Delete the rest of the objects $episode->delete(); $user->delete(); $subreddit->delete(); }
/** * add an episode to the patient for the given Firm * * @param $firm * @return Episode * @throws Exception */ public function addEpisode($firm) { $episode = new Episode(); $episode->patient_id = $this->id; if ($firm->getSubspecialtyID()) { $episode->firm_id = $firm->id; } else { $episode->support_services = true; } $episode->start_date = date("Y-m-d H:i:s"); if (!$episode->save()) { OELog::log("Unable to create new episode for patient_id={$episode->patient_id}, firm_id={$episode->firm_id}, start_date='{$episode->start_date}'"); throw new Exception('Unable to create create episode: ' . print_r($episode->getErrors(), true)); } OELog::log("New episode created for patient_id={$episode->patient_id}, firm_id={$episode->firm_id}, start_date='{$episode->start_date}'"); $episode->audit('episode', 'create'); Yii::app()->event->dispatch('episode_after_create', array('episode' => $episode)); return $episode; }
/** * This tests whether the * EpisodeAssignmentTable::getFirstByUserAuthorTypeAndSubreddit() function * retrieves the correct EpisodeAssignment for a particular User in a * Subreddit based on the AuthorType used in the EpisodeAssignment. Users * can sign up for one Episode per AuthorType in each Subreddit, which means * future Episodes (sicne we don't want the existence of past episode to * disqualify Users from ever signing up again). */ public function testGetFirstByUserAuthorTypeAndSubreddit() { // Create two episode assignments: one for a past Episode, one for a future $subreddit = new Subreddit(); $subreddit->setName(rand(0, 10000)); $subreddit->setDomain(rand(0, 10000)); $subreddit->save(); $user = new sfGuardUser(); $user->setUsername(rand(0, 10000)); $user->setEmailAddress(rand(0, 10000)); $user->setisValidated(1); $user->save(); $first = AuthorTypeTable::getInstance()->findOneBy('type', 'squid'); $understudy = AuthorTypeTable::getInstance()->findOneBy('type', 'shark'); $this->assertTrue($first instanceof AuthorType); $this->assertNotEquals(null, $first->getIncremented()); $this->assertTrue($understudy instanceof AuthorType); $this->assertNotEquals(null, $understudy->getIncremented()); $deadline_one = new Deadline(); $deadline_one->setSeconds(100); $deadline_one->setAuthorType($first); $deadline_one->setSubreddit($subreddit); $deadline_one->save(); $deadline_two = new Deadline(); $deadline_two->setSeconds(0); $deadline_two->setAuthorType($understudy); $deadline_two->setSubreddit($subreddit); $deadline_two->save(); $episode_one = new Episode(); $episode_one->setReleaseDate(date('Y-m-d H:i:s', time() + 200000)); $episode_one->setSubreddit($subreddit); $episode_one->save(); $episode_two = new Episode(); $episode_two->setReleaseDate(date('Y-m-d H:i:s', time() + 100000)); $episode_two->setSubreddit($subreddit); $episode_two->save(); $episode_three = new Episode(); $episode_three->setReleaseDate(date('Y-m-d H:i:s', time() + 300000)); $episode_three->setSubreddit($subreddit); $episode_three->save(); $assignment_one = new EpisodeAssignment(); $assignment_one->setEpisode($episode_one); $assignment_one->setSfGuardUser($user); $assignment_one->setAuthorType($first); $assignment_one->save(); $assignment_two = new EpisodeAssignment(); $assignment_two->setEpisode($episode_two); $assignment_two->setSfGuardUser($user); $assignment_two->setAuthorType($understudy); $assignment_two->save(); /* There should only be one Episode Assignment for future episodes per * authortype per subreddit, so saving the third assignment should fail * --- this is covered more in EpisodeAssignmentTest.phop */ $exception_thrown = false; $assignment_three = new EpisodeAssignment(); $assignment_three->setEpisode($episode_three); $assignment_three->setSfGuardUser($user); $assignment_three->setAuthorType($first); try { $assignment_three->save(); } catch (Exception $exception) { $exception_thrown = true; $this->assertEquals(102, $exception->getCode()); unset($exception); } $this->assertTrue($exception_thrown); /* Since we can trust that only one assignment per authortype per user * per subreddit exists for future episodes (based on the failure to * save $assignment_three), we check now to ensure that the * getFirstByUserAuthorTypeAndSubreddit() function returns a valid * EpisodeAssignment. */ $test_one = EpisodeAssignmentTable::getInstance()->getFirstByUserAuthorTypeAndSubreddit($assignment_one->getAuthorTypeId(), $assignment_one->getSfGuardUserId(), $assignment_one->getEpisode()->getSubredditId()); $test_two = EpisodeAssignmentTable::getInstance()->getFirstByUserAuthorTypeAndSubreddit($assignment_two->getAuthorTypeId(), $assignment_two->getSfGuardUserId(), $assignment_two->getEpisode()->getSubredditId()); $this->assertEquals($test_one->getIncremented(), $assignment_one->getIncremented()); $this->assertEquals($test_two->getIncremented(), $assignment_two->getIncremented()); $assignment_one->delete(); $assignment_two->delete(); $episode_one->delete(); $episode_two->delete(); $episode_three->delete(); $deadline_one->delete(); $deadline_two->delete(); $user->delete(); $subreddit->delete(); }
public function actionImport($importDir, $archiveDir, $errorDir, $dupDir, $interval = 'PT45M', $pasImport = false) { $this->importDir = $this->checkSeparator($importDir); $this->archiveDir = $this->checkSeparator($archiveDir); $this->errorDir = $this->checkSeparator($errorDir); $this->dupDir = $this->checkSeparator($dupDir); $this->interval = $interval; $fhirMarshal = Yii::app()->fhirMarshal; $eventType = EventType::model()->find('class_name=:class_name', array(':class_name' => 'OphInVisualfields')); if (!$eventType) { echo 'Cannot find OphInVisualfields event type, cannot continue' . PHP_EOL; die; } echo 'Processing FMES files...' . PHP_EOL; $filenames = glob($this->importDir . '/*.fmes'); echo count($filenames) . " files to process\n"; foreach ($filenames as $file) { try { $basename = basename($file); echo $basename . PHP_EOL; // First check the file has not already been imported: $field = file_get_contents($file); $fieldObject = $fhirMarshal->parseXml($field); if ($protected_file = ProtectedFile::model()->find('name=:name', array(':name' => $fieldObject->file_reference))) { echo '- ProtectedFile exists (' . $protected_file->id . ')' . PHP_EOL; $this->move($this->dupDir, $file); continue; } // Extract the patient number $matches = array(); preg_match('/__OE_PATIENT_ID_([0-9]*)__/', $field, $matches); if (count($matches) < 2) { echo '- Failed to extract patient ID' . PHP_EOL; $this->move($this->errorDir, $file); continue; } $match = str_pad($matches[1], 7, '0', STR_PAD_LEFT); // Fetch the patient if ($pasImport) { $model = new Patient(null); $model->hos_num = $match; $results = $model->search()->getData(); $patient = reset($results); } else { $patient = Patient::model()->find('hos_num=:hos_num', array(':hos_num' => $match)); } if (!$patient) { echo "- Failed to find patient ({$match})" . PHP_EOL; $this->move($this->errorDir, $file); continue; } $pid = $patient->id; $field = preg_replace('/__OE_PATIENT_ID_([0-9]*)__/', $pid, $field); // Convert to measurement $resource_type = 'MeasurementVisualFieldHumphrey'; $service = Yii::app()->service->getService($resource_type); $fieldObject = $fhirMarshal->parseXml($field); $tx = Yii::app()->db->beginTransaction(); $ref = $service->fhirCreate($fieldObject); $tx->commit(); $refId = $ref->getId(); $measurement = OphInVisualfields_Field_Measurement::model()->findByPk($refId); $study_datetime = $measurement->study_datetime; // Check for existing legacy events if (!($episode = Episode::model()->find('legacy = 1 AND patient_id = :patient_id', array(':patient_id' => $pid)))) { echo '- No legacy episode found, creating...'; $episode = new Episode(); $episode->legacy = 1; $episode->patient_id = $pid; $episode->save(); echo 'done' . PHP_EOL; // As there are no previous legacy events, we can create a new event $this->newEvent($episode, $eventType, $measurement); $this->move($this->archiveDir, $file); } else { // There is a legacy episode, so there may be unmatched legacy field events $criteria = new CdbCriteria(); $criteria->condition = 'event_type_id = :event_type_id and t.deleted = 0 and ep.deleted = 0 and ep.legacy = 1 and ep.patient_id = :patient_id'; $criteria->join = 'join episode ep on ep.id = t.episode_id'; $criteria->order = 't.event_date desc'; $criteria->params = array(':patient_id' => $pid, ':event_type_id' => $eventType->id); if ($this->interval) { // we're looking for all events that are bound to a legacy episode, // for the given patient, looking for the last created test - // this accounts for multiple tests per eye - the implication // being that the newest test overrides the last test for the same eye // (e.g. when a mistake is made and the test is re-ran): // Base time on interval defined by user, a narrow time slot that the test falls within $startCreatedTime = new DateTime($study_datetime); $endCreatedTime = new DateTime($study_datetime); $startCreatedTime->sub(new DateInterval($this->interval)); $endCreatedTime->add(new DateInterval($this->interval)); $criteria->condition .= ' AND t.event_date >= STR_TO_DATE("' . $startCreatedTime->format('Y-m-d H:i:s') . '", "%Y-%m-%d %H:%i:%s") AND t.event_date <= STR_TO_DATE("' . $endCreatedTime->format('Y-m-d H:i:s') . '", "%Y-%m-%d %H:%i:%s")'; } // Of events, there can only be one or none: // FIXME: This can return multiple events, so how do we choose? $events = Event::model()->findAll($criteria); if (count($events) == 1) { echo '- Found existing event (' . $events[0]->id . ')' . PHP_EOL; $element = Element_OphInVisualfields_Image::model()->find('event_id = :event_id', array(':event_id' => $events[0]->id)); $side = strtolower($measurement->eye->name); if ($existing = $element->{"{$side}_field"}) { if ($measurement->study_datetime > $existing->study_datetime) { echo "Newer than existing measurement on {$side}, overwriting\n"; $element->{"{$side}_field_id"} = $measurement->id; $unattached = $existing; } else { echo "Older than existing measurement on {$side}, ignoring\n"; $unattached = $measurement; } // Add dummy reference for the unattached measurement $ref = new MeasurementReference(); $ref->patient_measurement_id = $unattached->getPatientMeasurement()->id; $ref->save(); } else { echo "No existing measurement on {$side}, adding\n"; $element->{"{$side}_field_id"} = $measurement->id; } $element->save(); $this->move($this->archiveDir, $file); } elseif (count($events) > 1) { echo '- Found more than one matching event, cannot attach' . PHP_EOL; $this->move($this->errorDir, $file); } else { // No events in match window, so we create a new one $this->newEvent($episode, $eventType, $measurement); $this->move($this->archiveDir, $file); } } } catch (Exception $ex) { echo $ex . PHP_EOL; if (@$tx && $tx->active) { echo '- rolling back tx' . PHP_EOL; $tx->rollback(); } $this->move($this->errorDir, $file); } } }
/** * Creates or updates the episode in database getting data from file. * Used in /tvshow/actions/executeRefreshTVShow * * @param Season $season_object ex: Season(1) * @param Array $episode_info[] ex: [12, Getting in troubles, 1080p, 25 fps, 2300 kbps, 1920x800, [Spa,Eng], [Spa]] * @return Episode */ public static function createEpisode($season_object, $episode_info) { //looking for this episode in db $episode_object = NULL; foreach ($season_object['Episodes'] as $episode) { if ($episode->title == $episode_info['title']) { $episode_object = $episode; } } //if there is no episode if ($episode_object == NULL) { $episode_object = new Episode(); $episode_object->title = $episode_info['title']; $episode_object->num_episode = $episode_info['num_episode']; } $episode_object->duration = $episode_info['duration']; $episode_object->framerate = $episode_info['framerate']; $episode_object->bitrate = $episode_info['bitrate']; $episode_object->filesize = $episode_info['filesize']; $episode_object->dimensions = $episode_info['dimensions']; $episode_object->file_abs = $episode_info['file_abs']; $episode_object->file_rel = $episode_info['file_rel']; /*********************************** FORMAT ***********************************/ if ($episode_info['format'] != NULL) { $format_object = Doctrine::getTable('Format')->findOneByName($episode_info['format']); if ($format_object == NULL) { $format_object = Util::createFormat($episode_info['format']); } $episode_object->Format = $format_object; } /********************************** LANGUAGES **********************************/ //First remove previous audio tracks foreach ($episode_object['AudioTracks'] as $track) { $q = Doctrine_Query::create()->delete('AudioTrack')->where('id = ?', $track['id'])->execute(); } //Adding the new ones foreach ($episode_info['audio_tracks'] as $track) { $audio_track = Util::createAudioTrack($track['codec'], $track['code']); $episode_object->AudioTracks[] = $audio_track; } /********************************** SUBTITLES **********************************/ //First remove previous sub tracks foreach ($episode_object['SubTracks'] as $track) { $q = Doctrine_Query::create()->delete('SubTrack')->where('id = ?', $track['id'])->execute(); } //Adding the new ones foreach ($episode_info['sub_tracks'] as $track) { $sub_track = Util::createSubTrack($track['label'], $track['code']); $episode_object->SubTracks[] = $sub_track; } $episode_object->save(); $season_object->Episodes[] = $episode_object; $season_object->save(); return $episode_object; }