/** * @param \SimpleXMLElement $xml * @return Track */ public function transform(\SimpleXMLElement $xml) { $track = new Track(); $track->setArtist((string) $xml->artist); $track->setTitle((string) $xml->title); return $track; }
public function addtrackAction() { $form = new App_Form_NewTrack(); if (!empty($_POST) && $form->isValid($_POST)) { $artists = new App_Table_Artist(); //-------------------------------- // Check the file info, and save //-------------------------------- $track = new Track(); $track->title = $form->getValue('title'); $track->artistId = $this->_artist->id; $track->releaseId = $form->getValue('releaseId'); $track->single = true; $track->publishDate = $form->getValue('publishDate'); $track->save(); $this->_flash->addMessage('Your track info has been saved.'); $file = new TrackFile(); $file->trackId = $track->id; $file->fileName = $form->audioFile->getFileName(); $file->mimeType = mime_content_type($file->fileName); $file->save(); $track->originalFileId = $file->id; $track->save(); $this->_flash->addMessage('The audio file for your track has been scheduled for injestion. Once the file has been injested, it will be available on the site.'); $form = new App_Form_NewTrack(); } $form->setDefault('releaseId', $this->_request->getParam('releaseId')); $form->setMethod('post'); $form->setAction('/dashboard/catalog/addtrack'); $this->view->form = $form; }
function showHistoryGetEntry() { require_once "track.php"; $track = new Track("", "", ""); $entry = $track->getEntry(loadvar("trid")); return $entry["value"]; exit; }
public function removeTrack(Track $track) { foreach ($this->tracks as $k => $v) { if ($v->getNumber() == $track->getNumber()) { array_splice($this->tracks, $k, 1); } } $track->clear(); }
/** * store in db action * * @return array */ protected function track($action, $model, $id) { $track = new Track(); $track->auth_id = Auth::user()->id; $track->date = new Datetime(); $track->action = $action; $track->trackable_id = $id; $track->trackable_type = $model; return $track->save(); }
/** * scan a file for music * * @param string $path * @return boolean */ public function scanFile($path) { $mimeType = \OC\Files\Filesystem::getMimeType($path); if ($mimeType === 'application/ogg' or substr($mimeType, 0, 5) === 'audio') { $track = new Track($path); $data = $track->getTags(); if (!empty($data)) { $artistId = $this->collection->addArtist($data['artist']); $albumId = $this->collection->addAlbum($data['album'], $artistId); $this->collection->addSong($data['title'], $path, $artistId, $albumId, $data['length'], $data['track'], $data['size']); } } return true; }
/** * Check log directory for write access and if it's not created, try to create it * @param string / directory for log error file(s) * @return boolean */ public static function resolveLogDir($dir) { if (!is_string($dir)) { print 'Route directory should be string (if you don\'t want to specify any directory, just set it to: \'/\' or leave it empty \'\').' . "\n"; return false; } if (strlen($dir) < 1 || $dir == ' ') { self::$dir = ''; $dir = '/'; } elseif ($dir == '/') { self::$dir = ''; } else { self::$dir = $dir . DS; } $path = $dir; //dirname($_SERVER['SCRIPT_FILENAME']).DS.self::$dir; if (!is_dir($path)) { if (!mkdir($path, 0766, true)) { print 'Cannot create log directory' . "\n"; return false; } } elseif (!is_writable($path)) { print 'Directory is not writable'; return false; } return true; }
public function testRemoveTrackFromAlbum() { $album = Album::create('id', 'Album name'); $album->addTrack(Track::create('id', 'Track name')); $album->removeTrack(Track::create('id', 'Track name')); $this->assertCount(0, $album->getTracks()); }
private function admin() { $today = strtotime('today'); $month = strtotime('first day of this month'); $last30 = strtotime('-30 days'); // Users statistics $users['today'] = number_format(User::whereGt('reg_date', $today)->count()); $users['month'] = number_format(User::whereGt('reg_date', $month)->count()); $users['last30'] = number_format(User::whereGt('reg_date', $last30)->count()); $users['total'] = number_format(User::count()); View::set('users', $users); // Playlists statistics $playlists['today'] = number_format(Playlist::whereGt('date', $today)->count()); $playlists['month'] = number_format(Playlist::whereGt('date', $month)->count()); $playlists['last30'] = number_format(Playlist::whereGt('date', $last30)->count()); $playlists['total'] = number_format(Playlist::count()); View::set('playlists', $playlists); // Tracks statistics $tracks = number_format(Track::count()); View::set('tracks', $tracks); // Tags statistics $tags = number_format(Tag::count()); View::set('tags', $tags); // Comments statistics $comments = number_format(Comment::count()); View::set('comments', $comments); // Likes $likes = number_format(PlaylistLike::count()); View::set('likes', $likes); // Reports $reports = number_format(Report::count()); View::set('reports', $reports); View::show('admin/admin'); }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $latitud = Input::get('latitud', 0); $longitud = Input::get('longitud', 0); // DB::table('tracks')->insert( array( // 'latitud' => $latitud, // 'longitud' => $longitud // )); $track = new Track(); $track->latitud = $latitud; $track->longitud = $longitud; $track->save(); $respuesta = array("state" => "ok", "message" => "todo ok"); // $personas = Persona::all(); return json_encode($respuesta); }
public static function onArticleSaveComplete($article, $user, $revision, $status) { wfProfileIn(__METHOD__); $insertedImages = Wikia::getVar('imageInserts'); $imageDeletes = Wikia::getVar('imageDeletes'); $changedImages = $imageDeletes; foreach ($insertedImages as $img) { $changedImages[$img['il_to']] = true; } $sendTrackEvent = false; foreach ($changedImages as $imageDBName => $dummy) { $title = Title::newFromDBkey($imageDBName); if (!empty($title)) { $mq = new self($title); $mq->unsetCache(); $sendTrackEvent = true; } } // send track event if embed change if ($sendTrackEvent) { Track::event('embed_change'); } wfProfileOut(__METHOD__); return true; }
/** * Create/update schema in database. */ public static function update_schema() { global $wpdb; $sql = "\n\n CREATE TABLE " . Track::table_name() . " (\n id int(11) NOT NULL AUTO_INCREMENT,\n stream_title varchar(200) NOT NULL,\n track_key varchar(200) NOT NULL,\n artist varchar(100) NOT NULL,\n title varchar(100) NOT NULL,\n play_count int(11) NOT NULL,\n vote_count int(11) NOT NULL,\n vote_total int(11) DEFAULT NULL,\n vote_average double DEFAULT NULL,\n PRIMARY KEY (id),\n UNIQUE KEY (track_key),\n KEY (vote_average),\n KEY (play_count),\n KEY (vote_count),\n KEY (vote_total)\n ) CHARACTER SET utf8;\n\n CREATE TABLE " . Play::table_name() . " (\n id int(11) NOT NULL AUTO_INCREMENT,\n time_utc datetime NOT NULL,\n track_id int(11) NOT NULL,\n stream_title varchar(200) NOT NULL,\n PRIMARY KEY (id),\n KEY (track_id),\n KEY (time_utc),\n CONSTRAINT " . Play::table_name() . "_ibfk_1 FOREIGN KEY (track_id) REFERENCES " . Track::table_name() . " (id)\n ) CHARACTER SET utf8;\n\n CREATE TABLE " . Vote::table_name() . " (\n id int(11) NOT NULL AUTO_INCREMENT,\n time_utc datetime NOT NULL,\n track_id int(11) NOT NULL,\n stream_title varchar(200) NOT NULL,\n value tinyint(4) NOT NULL,\n nick varchar(30) NOT NULL,\n user_id varchar(150) NOT NULL,\n is_authed bit(1) NOT NULL,\n deleted tinyint(4) NOT NULL DEFAULT '0',\n comment varchar(200) NULL,\n PRIMARY KEY (id),\n KEY (track_id),\n KEY (time_utc),\n KEY (nick),\n CONSTRAINT " . Vote::table_name() . "_ibfk_1 FOREIGN KEY (track_id) REFERENCES " . Track::table_name() . " (id)\n ) CHARACTER SET utf8;\n\n "; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta($sql); }
public function buyTrack($trackid, $albumid) { $userid = $this->session->userdata('userid'); $result = array("error" => FALSE); if (!$userid) { $result["error"] = "You must login!"; echo json_encode($result); } $user = new User($userid); $track = Track::loadTrack($trackid); if ($user->getCredit() < $track->getCost()) { //The user can't afford the track! $result["error"] = "You have insufficient funds to buy the track as it costs £" . sprintf("%01.2f", $track->getCost() / 100) . ", please top up your account"; echo json_encode($result); } else { //Buy the rights to the track if ($user->aquireRightsToTrack($trackid, $albumid)) { //The track was bought successfully $result["bought"] = TRUE; } else { $result["error"] = "Sorry, there was a problem buying the track. Please try again later"; } echo json_encode($result); } }
/** Get the most popular tracks on last.fm by country. * * @param string country A country name, as defined by the ISO 3166-1 country names standard. (Required) * @param string location A metro name, to fetch the charts for (must be within the country specified). (Optional) * @return array An array of Track objects. * * @static * @access public * @throws Error */ public static function getTopTracks($country, $location = null) { $xml = CallerFactory::getDefaultCaller()->call('geo.getTopTracks', array('country' => $country, 'location' => $location)); $tracks = array(); foreach ($xml->children() as $track) { $tracks[] = Track::fromSimpleXMLElement($track); } return $tracks; }
public function __construct($url, $arguments, $accept) { parent::__construct($url, $arguments, $accept); // set the queryTrackId and queryTrackExternal_Key Values $this->queryFileExternal_Key = $this->queryParameterId; $this->queryFileId = $this->getIDfromExternalKey($this->queryFileExternal_Key); $this->queryFileGUID = $this->getGUIDfromID($this->queryFileId); // always include external_key Values in the Result $this->external_keys = true; }
function index() { $this->load->static_model('Track'); //$this->load->view('welcome_message'); $search_res = Track::searchByGenre("opera"); //$data = array('search_res' => $search_res); //$this->load->view('search', $data); $t = $search_res[0]; print_r($t->getArtist()->getTracks()); /*foreach( as $t){ echo $t->getName().", artist: ".$t->getArtist()->getName().", album: ".$t->getAlbum()->getName().", genres: "; print_r($t->getGenres()); echo ", videos: "; print_r($t->getVideos())."<br />"; }*/ }
public function actionInject() { header('Content-type:application/json'); $post = Yii::app()->getRequest()->getPost('chart'); $weeks = $post['weeks']; $artists = array(); $tracks = array(); $chart_entries = array(); // traverse $week /* weeks : [ * { * week : 1, * year : 2008, * tracks : [{ * start : 0, * mark : 1, * position : 32, * track : "Sexual Eruption", * artist : "Snoop Dogg" * }] * } * ] */ foreach ($weeks as $week) { foreach ($week['tracks'] as $chart_entry) { // populate artists $artist_name = $chart_entry['artist']; $artist_hash = md5($artist_name); if (!isset($artists[$artist_hash])) { $artists[$artist_hash] = $artist_name; } // populate tracks $track_title = $chart_entry['track']; $track_hash = md5("{$track_title}\\%charty\\%{$artist_name}"); if (!isset($tracks[$track_hash])) { $tracks[$track_hash] = array('title' => $track_title, 'artist_hash' => $artist_hash); } // populate chart_entry_data $chart_entries[] = array('year' => $week['year'], 'week' => $week['week'], 'position' => $chart_entry['position'], 'track_hash' => $track_hash); } } $inserted_artists = Artist::insertMultiple($artists); $inserted_tracks = Track::insertMultiple($tracks); $inserted_chart_entries = ChartEntry::insertMultiple($chart_entries); echo json_encode(array('inserted_artists' => $inserted_artists, 'inserted_tracks' => $inserted_tracks, 'inserted_chart_entries' => $inserted_chart_entries)); }
/** * Gets track by url * @param string $url * @return string */ public static function search($query) { // create a client object with your app credentials $client = new Services_Soundcloud(Base::$g['soundcloud_client'], ''); // find all sounds $tracks = $client->get('tracks', array('q' => $query, 'limit' => 40)); $tracks = json_decode($tracks); $ret = array(); foreach ($tracks as $track) { $table = Track::create(); $table->scid = $track->id; $table->name = $track->title; $table->scurl = $track->permalink_url; $table->duration = round($track->duration / 1000); $table->save(); $ret[] = $table->orm->asArray(); } return $ret; }
public function &getTracks($userid, $start = 0, $display = 30) { if ($this->id == NULL) { throw new Exception("Missing playlist ID when getting playlist's tracks"); } if ($this->tracks == NULL) { $this->load->static_model('Track'); $query = "SELECT SQL_CALC_FOUND_ROWS a.name AS `album_name`, a.id AS `album_id`, t.*, art.id AS `artist_id`, art.name AS `artist_name`, ut.bought\n\t FROM `track` t, `artist` art,`album` a, `album_track` at, `playlist_track` pt\n\t LEFT JOIN `user_track` ut ON(ut.trackid = pt.trackid AND ut.userid = " . $this->db->escape($userid) . ")\n\t WHERE pt.playlistid = " . $this->db->escape($this->id) . " AND pt.albumid = a.id AND pt.trackid = t.id \n\t AND t.main_artistid = art.id AND t.id = at.`trackid` AND a.id = at.`albumid` ORDER BY pt.`play_order`"; if ($display > 0) { $query .= " LIMIT {$start}, {$display}"; } $this->tracks = Track::getTrackList($query); } $result = array("tracks" => NULL, "rows" => NULL); $result["tracks"] = $this->tracks; $res = $this->db->query("SELECT FOUND_ROWS() AS num_rows")->first_row(); $result["rows"] = $res->num_rows; return $result; }
/** * get the tracks where this * artist is the main * @return array of Track */ public function getTracks() { if ($this->artistid == NULL) { throw new Exception("Missing track ID when requesting artist' track"); } //find the track id $query = "SELECT trackid FROM artist_track WHERE artistid = " . $this->db->escape($this->artistid); $tids = $this->db->query($query)->result(); if (count($tids) > 0) { $track_ids = ""; foreach ($tids as $tid) { $track_ids .= $tid->trackid . ","; } //remove the last comma $track_ids = substr($track_ids, 0, -1); $query = "SELECT a.`year`, a.name AS `album_name`, a.id AS `album_id`, t.*, art.id AS `artist_id`, art.name AS `artist_name`\n FROM `album_track` at, `track` t, `artist` art,`album` a, `track_genre` tg, `genre` g\n \n WHERE t.main_artistid = art.id AND t.id in ({$track_ids}) \n AND t.id = at.`trackid` AND a.id = at.`albumid` AND g.id = tg.genreid AND t.id = tg.trackid \n ORDER BY a.`year`"; return Track::getTrackList($query); } return array(); }
/** * {@inheritDoc} */ public static function fromObject($object) { $retval = new Album(); $retval->ids = (array) $object->ids; $retval->title = $object->title; $retval->primaryArtists = Artist::fromObjectArray((array) $object->primaryArtists); $retval->guestArtists = Artist::fromObjectArray((array) $object->guestArtists); $retval->flags = $object->flags; $retval->duration = $object->duration; $retval->originalReleaseDate = $object->originalReleaseDate; $retval->rating = $object->rating; $retval->isPick = $object->isPick; $retval->genres = Genre::fromObjectArray((array) $object->genres); $retval->headlineReview = $object->headlineReview; $retval->classicalReview = ClassicalReview::fromObject($object->classicalReview); $retval->credits = Credit::fromObjectArray((array) $object->credits); $retval->tracks = Track::fromObjectArray((array) $object->tracks); $retval->styles = Style::fromObjectArray((array) $object->styles); return $retval; }
function index() { $userid = $this->session->userdata('userid'); $playlists = $user = NULL; $mb_genres = $mb_artists = $mb_albums = NULL; if ($userid) { $this->load->static_model('Playlist'); $playlists = Playlist::getUsersPlaylists($userid); $user = new User($userid); if ($this->input->post("music_browser")) { $mb_genres = Track::getUserGenres($userid); $mb_artists = Track::getUserArtists($userid); $mb_albums = Track::getUserAlbums($userid); } else { $mb_genres = Track::getUserGenres($userid); $mb_artists = Track::getUserArtists($userid); $mb_albums = Track::getUserAlbums($userid); } } $data = array('userid' => $userid, 'user' => $user, 'playlists' => $playlists, 'page_title' => "Welcome.", 'dark' => TRUE, 'mb_genres' => $mb_genres, 'mb_artists' => $mb_artists, 'mb_albums' => $mb_albums); $this->load->view("common/header.php", $data); $this->load->view("main/main_view.php"); $this->load->view("common/footer.php"); }
/** * @covers Application\Entity\Track::setPto */ public function testSetPto() { $this->assertEquals($this->object, $this->object->setPto('HTM')); }
public function performGet($url, $arguments, $accept) { $track = new Track($url, $arguments, $accept); $response = $track->getResponseObject($this->getResponseContentType()); $this->sendResponse($response); }
<table class="table-hover"> <tr> <th><b><h3>Nombre</b></h3></th> <th><b><h3>Album</b></h3></th> <th><b><h3>Artista</b></h3></th> <th><b><h3>Duracion</b></h3></th> <th><b><h3>Tamaño</b></h3></th> <th></th> </tr> <?php $offset = isset($_GET['o']) ? $_GET['o'] : 0; $num = Track::all(1000); $numero_filas = Track::total(); ?> <?php foreach (Track::all(10, $offset) as $track) { ?> <tr id='<?php echo $track->TrackId; ?> '> <td> <button class='btn btn-default btn-sm button' type='button' onclick='modalEdit(<?php echo utf8_encode($track->TrackId); ?> )'><?php echo $track->Name; ?> </button>
/** * Scan the specified folder and subfolders, insert in the library the files found. * * @param string $folder Root folder to scan * * @return array Tracks inserted */ public function addFiles($folder) { require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/Artist.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/Album.php'; $result = array(); $this->scanFolders($folder, $this->folders); foreach ($this->files as $file) { //reset timeout for 20 seconds before processing each file set_time_limit(20); $track = new Track(); $track->file = $file; $trackInfo = $track->readId3(); if (key_exists('comments_html', $trackInfo)) { //ID3 has been found, we can use it if (key_exists('title', $trackInfo['comments_html'])) { $track->title = $trackInfo['comments_html']['title'][0]; } if (key_exists('album', $trackInfo['comments_html'])) { $track->albumName = $trackInfo['comments_html']['album'][0]; } if (key_exists('artist', $trackInfo['comments_html'])) { $track->artistName = $trackInfo['comments_html']['artist'][0]; } if (key_exists('track_number', $trackInfo['comments_html'])) { $track->track = intval($trackInfo['comments_html']['track_number'][0]); } if (key_exists('year', $trackInfo['comments_html'])) { $track->year = intval($trackInfo['comments_html']['year'][0]); } if (key_exists('audio', $trackInfo) && key_exists('bitrate_mode', $trackInfo['audio'])) { $track->mode = $trackInfo['audio']['bitrate_mode']; } if (key_exists('audio', $trackInfo) && key_exists('bitrate', $trackInfo['audio'])) { $track->bitrate = intval($trackInfo['audio']['bitrate']); } if (key_exists('playtime_seconds', $trackInfo)) { $track->time = intval($trackInfo['playtime_seconds']); } if (key_exists('filesize', $trackInfo)) { $track->size = intval($trackInfo['filesize']); } } if (!isset($track->title, $track->albumName, $track->artistName)) { //We use the filesystem pattern /path/artistName/albumName/title.ext $elements = explode('/', $file); $title = str_replace('-', ' ', str_replace('_', ' ', end($elements))); $albumName = str_replace('-', ' ', str_replace('_', ' ', prev($elements))); $artistName = str_replace('-', ' ', str_replace('_', ' ', prev($elements))); if (!isset($track->title)) { $track->title = $title; } if (!isset($track->albumName)) { $track->albumName = $albumName; } if (!isset($track->artistName)) { $track->artistName = $artistName; } } //insert/update artist $artist = new Artist(); $track->artist = $artist->insertIfRequired($track->artistName, null); //insert/update album $album = new Album(); $track->album = $album->insertIfRequired($track->albumName, null, $track->artist); //insert track if ($track->insert()) { //add to the returned array array_push($result, $track->structureData($track)); } } //return inserted files return $result; }
function handleTrackNode(&$conference, &$schedConf, &$trackNode, &$errors, &$user, $isCommandLine, &$dependentItems, $trackIndex = null) { $trackDao =& DAORegistry::getDAO('TrackDAO'); $errors = array(); $schedConfSupportedLocales = array_keys($schedConf->getSupportedLocaleNames()); // => sched conf locales must be set up before $schedConfPrimaryLocale = $schedConf->getPrimaryLocale(); // The following page or two is responsible for locating an // existing track based on title and/or abbrev, or, if none // can be found, creating a new one. $titles = array(); for ($index = 0; $node = $trackNode->getChildByName('title', $index); $index++) { $locale = $node->getAttribute('locale'); if ($locale == '') { $locale = $schedConfPrimaryLocale; } elseif (!in_array($locale, $schedConfSupportedLocales)) { $errors[] = array('plugins.importexport.native.import.error.trackTitleLocaleUnsupported', array('trackTitle' => $node->getValue(), 'locale' => $locale)); return false; // or ignore this error? } $titles[$locale] = $node->getValue(); } if (empty($titles)) { $errors[] = array('plugins.importexport.native.import.error.trackTitleMissing'); return false; } $abbrevs = array(); for ($index = 0; $node = $trackNode->getChildByName('abbrev', $index); $index++) { $locale = $node->getAttribute('locale'); if ($locale == '') { $locale = $schedConfPrimaryLocale; } elseif (!in_array($locale, $schedConfSupportedLocales)) { $errors[] = array('plugins.importexport.native.import.error.trackAbbrevLocaleUnsupported', array('trackAbbrev' => $node->getValue(), 'locale' => $locale)); return false; // or ignore this error? } $abbrevs[$locale] = $node->getValue(); } $identifyTypes = array(); for ($index = 0; $node = $trackNode->getChildByName('identify_type', $index); $index++) { $locale = $node->getAttribute('locale'); if ($locale == '') { $locale = $schedConfPrimaryLocale; } elseif (!in_array($locale, $schedConfSupportedLocales)) { $errors[] = array('plugins.importexport.native.import.error.trackIdentifyTypeLocaleUnsupported', array('trackIdentifyType' => $node->getValue(), 'locale' => $locale)); return false; // or ignore this error? } $identifyTypes[$locale] = $node->getValue(); } $policies = array(); for ($index = 0; $node = $trackNode->getChildByName('policy', $index); $index++) { $locale = $node->getAttribute('locale'); if ($locale == '') { $locale = $schedConfPrimaryLocale; } elseif (!in_array($locale, $schedConfSupportedLocales)) { $errors[] = array('plugins.importexport.native.import.error.trackPolicyLocaleUnsupported', array('trackPolicy' => $node->getValue(), 'locale' => $locale)); return false; // or ignore this error? } $policies[$locale] = $node->getValue(); } // $title and, optionally, $abbrev contain information that can // be used to locate an existing track. Otherwise, we'll // create a new one. If $title and $abbrev each match an // existing track, but not the same track, throw an error. $track = null; $foundTrackId = $foundTrackTitle = null; $index = 0; foreach ($titles as $locale => $title) { $track = $trackDao->getTrackByTitle($title, $schedConf->getId()); if ($track) { $trackId = $track->getId(); if ($foundTrackId) { if ($foundTrackId != $trackId) { // Mismatching tracks found. Throw an error. $errors[] = array('plugins.importexport.native.import.error.trackTitleMismatch', array('track1Title' => $title, 'track2Title' => $foundTrackTitle)); return false; } } else { if ($index > 0) { // the current title matches, but the prev titles didn't => error $errors[] = array('plugins.importexport.native.import.error.trackTitleMatch', array('trackTitle' => $title)); return false; } } $foundTrackId = $trackId; $foundTrackTitle = $title; } else { if ($foundTrackId) { // a prev title matched, but the current doesn't => error $errors[] = array('plugins.importexport.native.import.error.trackTitleMatch', array('trackTitle' => $foundTrackTitle)); return false; } } $index++; } // check abbrevs: $abbrevTrack = null; $foundTrackId = $foundTrackAbbrev = null; $index = 0; foreach ($abbrevs as $locale => $abbrev) { $abbrevTrack = $trackDao->getTrackByAbbrev($abbrev, $schedConf->getId()); if ($abbrevTrack) { $trackId = $abbrevTrack->getTrackId(); if ($foundTrackId) { if ($foundTrackId != $trackId) { // Mismatching tracks found. Throw an error. $errors[] = array('plugins.importexport.native.import.error.trackAbbrevMismatch', array('track1Abbrev' => $abbrev, 'track2Abbrev' => $foundTrackAbbrev)); return false; } } else { if ($index > 0) { // the current abbrev matches, but the prev abbrevs didn't => error $errors[] = array('plugins.importexport.native.import.error.trackAbbrevMatch', array('trackAbbrev' => $trackAbbrev)); return false; } } $foundTrackId = $trackId; $foundTrackAbbrev = $abbrev; } else { if ($foundTrackId) { // a prev abbrev matched, but the current doesn't => error $errors[] = array('plugins.importexport.native.import.error.trackAbbrevMatch', array('trackAbbrev' => $foundTrackAbbrev)); return false; } } $index++; } if (!$track && !$abbrevTrack) { // The track was not matched. Create one. // Note that because tracks are global-ish, // we're not maintaining a list of created // tracks to delete in case the import fails. unset($track); $track = new Track(); $track->setTitle($titles, null); $track->setAbbrev($abbrevs, null); $track->setIdentifyType($identifyTypes, null); $track->setPolicy($policies, null); $track->setSchedConfId($schedConf->getId()); $track->setSequence(REALLY_BIG_NUMBER); $track->setMetaIndexed(1); $track->setEditorRestricted(1); $track->setTrackId($trackDao->insertTrack($track)); $trackDao->resequenceTracks($schedConf > getSchedConfId()); } if (!$track && $abbrevTrack) { unset($track); $track =& $abbrevTrack; } // $track *must* now contain a valid track, whether it was // found amongst existing tracks or created anew. $hasErrors = false; for ($index = 0; $node = $trackNode->getChildByName('paper', $index); $index++) { if (!NativeImportDom::handlePaperNode($conference, $schedConf, $node, $track, $paper, $publishedPaper, $paperErrors, $user, $isCommandLine, $dependentItems)) { $errors = array_merge($errors, $paperErrors); $hasErrors = true; } } if ($hasErrors) { return false; } return true; }
/** * Returns a specific user's track by it sequence number. * * @return mixed|bool track on success, or false on error. */ public function get() { require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/Track.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/DatabaseConnection.php'; $connection = new DatabaseConnection(); $query = $connection->prepare('SELECT `track`.`id`, `track`.`title`, `track`.`artist`, `artist`.`name` AS `artistName`, `track`.`album`, `album`.`name` AS `albumName`, `track`.`id` AS `file`, `playlist`.`userId` , `playlist`.`sequence`, `cover`.`albumId` AS `coverId` FROM `track`, `artist`, `playlist`, `album` LEFT JOIN `cover` ON `album`.`id`=`cover`.`albumId` AND `cover`.`status` = 1 WHERE `track`.`artist`=`artist`.`id` AND `track`.`album`=`album`.`id` AND `track`.`id`=`playlist`.`id` AND `playlist`.`userId`=:userId AND `playlist`.`sequence`=:sequence LIMIT 1;'); $query->bindValue(':userId', $this->userId, PDO::PARAM_INT); $query->bindValue(':sequence', $this->sequence, PDO::PARAM_INT); $query->execute(); $query->setFetchMode(PDO::FETCH_INTO, $this); if ($query->fetch()) { $trackStructured = new Track(); //returns structured track return $trackStructured->structureData($this); } //returns false to indicate there is no such a track for this user return false; }
/** A paginated list of all the tracks in a user's library, with play counts and tag counts. * * @param string $user The user whose library you want to fetch. (Required) * @param integer $limit Limit the amount of tracks returned (maximum/default is 50). (Optional) * @param integer $page The page number you wish to scan to. (Optional) * @return PaginatedResult A PaginatedResult object. * * @static * @access public * @throws Error */ public static function getTracks($user, $limit, $page) { $xml = CallerFactory::getDefaultCaller()->call('library.getTracks', array('user' => $user, 'limit' => $limit, 'page' => $page)); $tracks = array(); foreach ($xml->children() as $track) { $tracks[] = Track::fromSimpleXMLElement($track); } $perPage = Util::toInteger($xml['perPage']); return new PaginatedResult(Util::toInteger($xml['totalPages']) * $perPage, (Util::toInteger($xml['page']) - 1) * $perPage, $perPage, $tracks); }
/** * Import papers (including metadata and files). */ function importPapers() { if ($this->hasOption('verbose')) { printf("Importing papers\n"); } import('classes.file.PaperFileManager'); import('classes.search.PaperSearchIndex'); $userDao =& DAORegistry::getDAO('UserDAO'); $roleDao =& DAORegistry::getDAO('RoleDAO'); $trackDao =& DAORegistry::getDAO('TrackDAO'); $paperDao =& DAORegistry::getDAO('PaperDAO'); $publishedPaperDao =& DAORegistry::getDAO('PublishedPaperDAO'); $galleyDao =& DAORegistry::getDAO('PaperGalleyDAO'); $unassignedTrackId = null; $result =& $this->importDao->retrieve('SELECT * FROM papers ORDER by id'); while (!$result->EOF) { $row =& $result->fields; $schedConf =& $this->schedConfMap[$row['cf']]; $schedConfId = $schedConf->getId(); // Bring in the primary user for this paper. $user = $userDao->getUserByUsername(Core::cleanVar($row['login'])); if (!$user) { unset($user); $user = new User(); $user->setUsername(Core::cleanVar($row['login'])); $user->setFirstName(Core::cleanVar($row['first_name'])); $user->setLastName(Core::cleanVar($row['surname'])); $user->setAffiliation(Core::cleanVar($row['affiliation']), Locale::getLocale()); $user->setEmail(Core::cleanVar($row['email'])); $user->setUrl(Core::cleanVar($row['url'])); $user->setBiography(Core::cleanVar($row['bio']), Locale::getLocale()); $user->setLocales(array()); $user->setDateRegistered($row['created']); $user->setDateLastLogin($row['created']); $user->setMustChangePassword(1); $password = Validation::generatePassword(); $user->setPassword(Validation::encryptCredentials($user->getUsername(), $password)); if ($this->hasOption('emailUsers')) { import('classes.mail.MailTemplate'); $mail = new MailTemplate('USER_REGISTER'); $mail->setFrom($schedConf->getSetting('contactEmail'), $schedConf->getSetting('contactName')); $mail->assignParams(array('username' => $user->getUsername(), 'password' => $password, 'conferenceName' => $schedConf->getFullTitle())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); } $user->setDisabled(0); $otherUser =& $userDao->getUserByEmail(Core::cleanVar($row['email'])); if ($otherUser !== null) { // User exists with this email -- munge it to make unique $user->setEmail('ocs-' . Core::cleanVar($row['login']) . '+' . Core::cleanVar($row['email'])); $this->conflicts[] = array(&$otherUser, &$user); } unset($otherUser); $userDao->insertUser($user); // Make this user a author $role = new Role(); $role->setSchedConfId($schedConf->getId()); $role->setConferenceId($schedConf->getConferenceId()); $role->setUserId($user->getId()); $role->setRoleId(ROLE_ID_AUTHOR); $roleDao->insertRole($role); unset($role); } $userId = $user->getId(); // Bring in the basic entry for the paper $paper = new Paper(); $paper->setUserId($userId); $paper->setLocale(Locale::getPrimaryLocale()); $paper->setSchedConfId($schedConfId); $oldTrackId = $row['primary_track_id']; if (!$oldTrackId || !isset($this->trackMap[$oldTrackId])) { $oldTrackId = $row['secondary_track_id']; } if (!$oldTrackId || !isset($this->trackMap[$oldTrackId])) { if (!$unassignedTrackId) { // Create an "Unassigned" track to use for submissions // that didn't have a track in OCS 1.x. $track = new Track(); $track->setSchedConfId($schedConf->getId()); $track->setTitle('UNASSIGNED', Locale::getLocale()); $track->setSequence(REALLY_BIG_NUMBER); $track->setDirectorRestricted(1); $track->setMetaReviewed(1); $unassignedTrackId = $trackDao->insertTrack($track); } $newTrackId = $unassignedTrackId; } else { $newTrackId = $this->trackMap[$oldTrackId]; } $paper->setTrackId($newTrackId); $paper->setTitle(Core::cleanVar($row['title']), Locale::getLocale()); $paper->setAbstract(Core::cleanVar($row['abstract']), Locale::getLocale()); $paper->setDiscipline(Core::cleanVar($row['discipline']), Locale::getLocale()); $paper->setSponsor(Core::cleanVar($row['sponsor']), Locale::getLocale()); $paper->setSubject(Core::cleanVar($row['topic']), Locale::getLocale()); $paper->setLanguage(Core::cleanVar($row['language'])); $paper->setDateSubmitted($row['created']); $paper->setDateStatusModified($row['timestamp']); // $paper->setTypeConst($row['present_format'] == 'multiple' ? SUBMISSION_TYPE_PANEL : SUBMISSION_TYPE_SINGLE); FIXME $paper->setCurrentRound(REVIEW_ROUND_ABSTRACT); $paper->setSubmissionProgress(0); $paper->setPages(''); // Bring in authors $firstNames = split("\n", Core::cleanVar($row['first_name'] . "\n" . $row['add_first_names'])); $lastNames = split("\n", Core::cleanVar($row['surname'] . "\n" . $row['add_surnames'])); $emails = split("\n", Core::cleanVar($row['email'] . "\n" . $row['add_emails'])); $affiliations = split("\n", Core::cleanVar($row['affiliation'] . "\n" . $row['add_affiliations'])); $urls = split("\n", Core::cleanVar($row['url'] . "\n" . $row['add_urls'])); foreach ($emails as $key => $email) { if (empty($email)) { continue; } $author = new Author(); $author->setEmail($email); $author->setFirstName($firstNames[$key]); $author->setLastName($lastNames[$key]); $author->setAffiliation($affiliations[$key], Locale::getLocale()); @$author->setUrl($urls[$key]); // Suppress warnings from inconsistent OCS 1.x data $author->setPrimaryContact($key == 0 ? 1 : 0); $paper->addAuthor($author); unset($author); } switch ($row['accepted']) { case 'true': $paper->setStatus(STATUS_PUBLISHED); $paperId = $paperDao->insertPaper($paper); $publishedPaper = new PublishedPaper(); $publishedPaper->setPaperId($paperId); $publishedPaper->setSchedConfId($schedConfId); $publishedPaper->setDatePublished(Core::getCurrentDate()); $publishedPaper->setSeq(REALLY_BIG_NUMBER); $publishedPaper->setViews(0); $publishedPaperDao->insertPublishedPaper($publishedPaper); $publishedPaperDao->resequencePublishedPapers($paper->getTrackId(), $schedConfId); break; case 'reject': $paper->setStatus(STATUS_DECLINED); $paperId = $paperDao->insertPaper($paper); break; default: $paper->setStatus(STATUS_QUEUED); $paperId = $paperDao->insertPaper($paper); } $this->paperMap[$row['id']] =& $paper; $paperFileManager = new PaperFileManager($paperId); if (!empty($row['paper']) && $row['paper'] != 'PDF') { $format = 'text/html'; $extension = $paperFileManager->getDocumentExtension($format); $fileId = $paperFileManager->writeSubmissionFile('migratedFile' . $extension, $row['paper'], $format); $paper->setSubmissionFileId($fileId); $paperDao->updatePaper($paper); $fileId = $paperFileManager->writePublicFile('migratedGalley' . $extension, $row['paper'], $format); PaperSearchIndex::updateFileIndex($paperId, PAPER_SEARCH_GALLEY_FILE, $fileId); if (strstr($format, 'html')) { $galley = new PaperHTMLGalley(); $galley->setLabel('HTML'); } else { $galley = new PaperGalley(); switch ($format) { case 'application/pdf': $galley->setLabel('PDF'); break; case 'application/postscript': $galley->setLabel('PostScript'); break; case 'application/msword': $galley->setLabel('Word'); break; case 'text/xml': $galley->setLabel('XML'); break; case 'application/powerpoint': $galley->setLabel('Slideshow'); break; default: $galley->setLabel('Untitled'); break; } } $galley->setLocale(Locale::getLocale()); $galley->setPaperId($paperId); $galley->setFileId($fileId); $galleyDao->insertGalley($galley); unset($galley); } elseif ($row['paper'] == 'PDF') { $fileId = $paperFileManager->copySubmissionFile($this->importPath . '/papers/' . $row['pdf'], 'application/pdf'); $paper->setSubmissionFileId($fileId); $paperDao->updatePaper($paper); $fileId = $paperFileManager->copyPublicFile($this->importPath . '/papers/' . $row['pdf'], 'application/pdf'); PaperSearchIndex::updateFileIndex($paperId, PAPER_SEARCH_GALLEY_FILE, $fileId); $galley = new PaperGalley(); $galley->setLabel('PDF'); $galley->setLocale(Locale::getLocale()); $galley->setPaperId($paperId); $galley->setFileId($fileId); $galleyDao->insertGalley($galley); unset($galley); } // FIXME: The following fields from OCS 1.x are UNUSED: // program_insert approach coverage format relation appendix_names appendix_dates // appendix appendix_pdf secondary_track_id multiple_* restrict_access paper_email // delete_paper comment_email unset($user); unset($paper); unset($schedConf); unset($paperFileManager); $result->MoveNext(); } $result->Close(); }