Location: PHPKode > projects > phpMUR Multi User Randomizer > new.pick.songs.php
<?php
	// session_start();

	$time_start = microtime(true);
	include_once 'config.inc.php';
	include_once 'inc/common.inc.php';
	include_once 'class/db.class.php';

	global $db, $session_preload, $session_playlist, $artist_threshold, $song_threshold;
	$session_preload = $session_playlist = array();

	$artist_threshold = 50;
	$song_threshold = 1000;
	$db = new db(DB_HOST, DB_NAME, DB_UNAME, DB_PWORD, $die = true);

	function prepare_tmp_tables_new() {
		global $db, $session_preload, $session_playlist, $song_threshold, $artist_threshold;
		static $ran = false;
		$fids = array();
		$aids = array();
		foreach ($session_preload as $f) {
			$fids["{$f['fid']}"] = $f['fid'];
			$aids["{$f['aid']}"] = $f['aid'];
		}
		foreach ($session_playlist as $f) {
			$fids["{$f['fid']}"] = $f['fid'];
			$aids["{$f['aid']}"] = $f['aid'];
		}
		if ($ran) {
			// I'm not sure this is needed, after all it should be ok if it's done once.
			/*
			// Add files that are in the playlist/preload
			if ($aids) {
				$db->equery("INSERT IGNORE INTO dont_pick_artists (aid, aid_cnt) VALUES (".implode(',1),(', $aids).",1)");
			}
			if ($fids) {
				$db->equery("INSERT IGNORE INTO dont_pick (fid) VALUES (".implode('),(', $fids).")");
			} */
			return;
		}
		$ran = true;

		$uids = '1,2,3,4';
		// $uids = implode(',',array_keys($_SESSION['users']));

		// Create dont_pick_artists
		$db->query('CREATE TEMPORARY TABLE `dont_pick_artists` (`aid` int(11) NOT NULL, `aid_cnt` int(11) NOT NULL, UNIQUE KEY `aid` (`aid`), KEY `aid_cnt` (`aid_cnt`))');

		// Add artists to dont_pick_artists
		if (!$uids) {
			// There are no users
			$db->query("INSERT IGNORE INTO dont_pick_artists (aid, aid_cnt) SELECT aid, '1' FROM artists WHERE altp != '0000-00-00 00:00:00' ORDER BY altp DESC LIMIT $artist_threshold");
		} else {
			// There are users.
			$db->query("INSERT IGNORE INTO dont_pick_artists (aid, aid_cnt) SELECT DISTINCT f.aid, '1' FROM files f, user_song_info u WHERE u.ultp != '0000-00-00 00:00:00' AND f.fid = u.fid AND u.uid IN ($uids) ORDER BY u.ultp DESC LIMIT $artist_threshold");
		}

		// Create dont_pick
		$db->query('CREATE TEMPORARY TABLE `dont_pick` (`fid` int(11) NOT NULL auto_increment,UNIQUE KEY `fid` (`fid`)) ENGINE=MyISAM DEFAULT CHARSET=latin1');

		// Add files that are in the playlist/preload
		if ($aids) {
			$db->equery("INSERT IGNORE INTO dont_pick_artists (aid, aid_cnt) VALUES (".implode(',1),(', $aids).",1)");
		}
		if ($fids) {
			$db->equery("INSERT IGNORE INTO dont_pick (fid) VALUES (".implode('),(', $fids).")");
		}

		// Add files to dont_pick
		if (!$uids) {
			// There are no users.
			$db->query("INSERT IGNORE INTO dont_pick (fid) SELECT DISTINCT fid FROM files WHERE ltp != '0000-00-00 00:00:00' ORDER BY ltp DESC LIMIT $song_threshold");
		} else {
			// There are users.
			$db->query("INSERT IGNORE INTO dont_pick (fid) SELECT DISTINCT f.fid FROM files f, user_song_info u WHERE u.ultp != '0000-00-00 00:00:00' AND u.uid IN ($uids) AND u.fid = f.fid ORDER BY ultp DESC LIMIT $song_threshold");
		}
		if ($uids) {
			// Add songs rated 0.
			$db->query("INSERT IGNORE INTO dont_pick (fid) SELECT fid FROM user_song_info WHERE uid IN ($uids) AND rating = '0'");
		}
	}

	function populate_preload_new($uid) {
		global $db, $session_preload, $session_playlist, $song_threshold, $artist_threshold;
		$files = array();
		prepare_tmp_tables_new();
		for($r=11;$r>0;$r--) {
			$query = "SELECT DISTINCT f.aid FROM files f LEFT JOIN dont_pick dp ON dp.fid = f.fid LEFT JOIN dont_pick_artists dpa ON dpa.aid = f.aid, user_song_info u, user_genres ug WHERE ug.uid = u.uid AND ug.gid = f.gid AND dp.fid IS NULL AND ((dpa.aid IS NULL) OR (dpa.aid_cnt > $artist_threshold AND dpa.aid = f.aid)) AND u.uid = $uid AND u.rating = $r AND u.fid = f.fid ORDER BY ltp, rand() LIMIT $r";
			$aids = $db->get_results_assoc($query);
			foreach ($aids as $a) {
				$query = "SELECT f.fid, a.aid, a.artist, f.title FROM files f  LEFT JOIN dont_pick dp ON dp.fid = f.fid, artists a, user_song_info u, user_genres ug WHERE u.fid = f.fid AND ug.uid = u.uid AND ug.gid = f.gid AND dp.fid IS NULL AND a.aid = f.aid AND a.aid = {$a['aid']} AND u.uid = $uid AND u.rating = $r ORDER BY u.ultp, rand() LIMIT 1";
				$f = $db->get_assoc($query);
				$db->query("INSERT IGNORE INTO dont_pick_artists (aid, aid_cnt) VALUES('{$f['aid']}','0')");
				$db->query("UPDATE dont_pick_artists SET aid_cnt = '0' WHERE aid = '{$f['aid']}'");
				$db->query("INSERT IGNORE INTO dont_pick (fid) VALUES('{$f['fid']}')");
				$db->query("UPDATE dont_pick_artists SET aid_cnt = aid_cnt + 1");
				$f['uid'] = $uid;
				$f['rating'] = $r;
				$files[] = $f;
			}
		}
		$session_preload = array_merge($session_preload,$files);

	}

	function shuffle_preload_old() {
		global $db, $session_preload, $session_playlist, $song_threshold, $artist_threshold;
		$files = $session_preload;
		$new_files = array();
		foreach ($files as $k=>$f) {
			if (!isset($f['uid']) || !$f['uid']) {
				$new_files[] = $f;
				unset($files["$k"]);
			}
		}
		$uids = array(1,2,3,4);
		// $uids = array_keys($_SESSION['users']);
		while ($files) {
			// foreach($_SESSION['users'] as $uid=>$uinfo) {}
			foreach ($uids as $uid) {
				foreach ($files as $k=>$f) {
					if ($f['uid'] == $uid) {
						$new_files[] = $f;
						unset($files["$k"]);
						continue 2;
					}
				}
			}
		}

		$artist_threshold = 100;
		$fcount = count($new_files);

		$apos = array();
		$spaced_files = array();
		$must_be_here = array();
		$doesnt_matter = array();

		foreach ($new_files as $k=>$f) {
			if (!isset($apos["{$f['aid']}"])) {
				$apos["{$f['aid']}"] = array();
			}
			sort($apos["{$f['aid']}"]);
			$last = end($apos["{$f['aid']}"]);
			if ($last) {
				$space = $k - $last;
				if ($space <= $artist_threshold) {
					$low_new_pos = ($last - $artist_threshold);
					$high_new_pos = ($last + $artist_threshold);
					/*
					echo "k:$k\n";
					echo "last:$last\n";
					echo "\$low_new_pos:$low_new_pos ($last - $artist_threshold)\n";
					echo "\$high_new_pos:$high_new_pos ($last + $artist_threshold)\n";
					echo "space:$space\n"; */
					if ($low_new_pos >= 0) {
						// echo "low:$low_new_pos > 0\n";
						$must_be_here["$low_new_pos"] = $f;
						$apos["{$f['aid']}"][] = $low_new_pos;
						sort($apos["{$f['aid']}"]);
						// echo "set low:$low_new_pos\n";
					} elseif ($high_new_pos <= $fcount) {
						// echo "high:$high_new_pos < $fcount\n";
						$apos["{$f['aid']}"][] = $high_new_pos;
						sort($apos["{$f['aid']}"]);
						$must_be_here["$high_new_pos"] = $f;
						// echo "set high:$high_new_pos\n";
					} else {
						/*
						echo "!low:$low_new_pos > 0\n";
						echo "!high:$high_new_pos < $fcount\n";
						echo "bad_number:$k\n";
						exit;  */
					}
					continue;
				} else {
					// Do nothing they are spaced properly.
				}
			}
			$doesnt_matter["$k"] = $f;
			$apos["{$f['aid']}"][] = $k;
		}

		$fcount = count($new_files);
		$spaced_files = $must_be_here;
		foreach ($doesnt_matter as $k=>$f) {
			if (!isset($spaced_files["$k"])) {
				$spaced_files["$k"] = $f;
			} else {
				$asc = false;
				while (isset($spaced_files["$k"])) {
					if ($k == 0) {
						$asc = true;
					} elseif ($k >= $fcount) {
						$asc = false;
					}
					if ($asc) {
						$k++;
					} else {
						$k--;
					}
				}
			}
		}
		ksort($spaced_files);
		$session_preload = $spaced_files;
		// echo $list."\n";

	}

	function shuffle_preload_new() {
		global $db, $session_preload, $session_playlist, $song_threshold, $artist_threshold;
		$files = $session_preload;
		$fcount = count($session_preload);
		shuffle($files);
		$groups = ceil($fcount / $artist_threshold);
		$files_per_chunk = ceil($fcount / $groups);
		// echo "\$fcount:$fcount\n";
		// echo "\$groups:$groups\n";
		// echo "\$files_per_chunk:$files_per_chunk\n";
		$aid_cnt = array();
		foreach ($files as $k=>$f) {
			$aid_cnt["{$f['aid']}"]++;
		}
		arsort($aid_cnt);
		// print_r($aid_cnt);
		$seperate = array();
		foreach ($aid_cnt as $aid=>$cnt) {
			if ($cnt >= 2) {
				foreach ($files as $k=>$f) {
					if ($f['aid'] == $aid) {
						$seperate[] = $f;
						unset($files["$k"]);
					}
				}
			}
		}
		// print_r($seperate);
		$chunked = array_chunk($files, $files_per_chunk);
		// $chunked_aids = array_chunk($aids, $files_per_chunk, true);
		//int array_unshift ( array &$array, mixed $var [, mixed $...] )
		while ($seperate) {
			foreach ($chunked as $k=>$fs) {
				$f = array_pop($seperate);
				if ($f) {
					array_unshift($chunked["$k"], $f);
				}
			}
		}
		$files = array();
		foreach ($chunked as $fs) {
			$files = array_merge($files, $fs);
		}
		$session_preload = $files;
	}

	$uids = array(1,2,3,4);
	foreach ($uids as $uid) {
		populate_preload_new($uid);
	}
	shuffle_preload_new();

	$apos = array();
	ob_start();
	foreach ($session_preload as $k=>$f) {
		$apos["{$f['aid']}"][] = $k;
	}
	foreach ($session_preload as $k=>$f) {
		echo "$k:".implode(',,',$apos["{$f['aid']}"]).":{$f['artist']} - {$f['title']}\n";
	}

	$list = ob_get_clean();
	$fp = fopen('tmp.list','w');
	fputs($fp, $list);
	fclose($fp);

	// prepare_tmp_tables_new();
	$time_end = microtime(true);
	$time = $time_end - $time_start;

	echo "$time seconds\n";

?>
Return current item: phpMUR Multi User Randomizer