function validateMediaOperation($opType = "ADD", $mediaObject = null) { $e = new Error(); // called automatically by the m2 functions that add media, when passed the object // opType allows us to distinguish between adding, editing, updating, etc... but most times // the same check will work for all operation types if ($opType == "UPDATEINFO") { if (!User::isAdmin()) { $e->add("Only an admin user may edit media areas."); return $e; } } if ($opType == "RESCAN") { if (!User::isAdmin()) { $e->add("Only an admin user may rescan media."); return $e; } } if (!$this->areaObject->isGeneralMedia()) { $e->add("You cannot directly move or edit an area that is not generally accessible."); return $e; } else { if (!User::isAdmin()) { $e->add("Only an admin user may modify general media."); return $e; } } // if we get this far... return true; }
/** * constructor * This should be called */ public function __construct($id = null, $cached = true) { $sid = session_id(); if (is_null($id)) { $this->reset(); if ($cached) { $data = serialize($this->_state); $sql = 'INSERT INTO `tmp_browse` (`sid`, `data`) ' . 'VALUES(?, ?)'; Dba::write($sql, array($sid, $data)); $this->id = Dba::insert_id(); } else { $this->id = 'nocache'; } return true; } $this->id = $id; $sql = 'SELECT `data` FROM `tmp_browse` ' . 'WHERE `id` = ? AND `sid` = ?'; $db_results = Dba::read($sql, array($id, $sid)); if ($results = Dba::fetch_assoc($db_results)) { $this->_state = unserialize($results['data']); return true; } Error::add('browse', T_('Browse not found or expired, try reloading the page')); return false; }
/** * set * * This sets config values. */ public static function set($name, $value, $clobber = false) { if (isset(self::$_global[$name]) && !$clobber) { debug_event('Config', "Tried to overwrite existing key {$name} without setting clobber", 5); Error::add('Config Global', sprintf(T_('Trying to clobber \'%s\' without setting clobber'), $name)); return false; } self::$_global[$name] = $value; }
function getAVAreaObject() { if ($this->av_area_id > 0) { $ma = MediaArea::get($this->av_area_id); return $ma; } else { $e = new Error(); $e->add("An administrator has not yet registered this track for audio or videos."); return $e; } }
debug_event('Login', scrub_out($username) . ' is already logged in from ' . $session_ip . ' and attempted to login from ' . $current_ip, '1'); } // if logged in multiple times } elseif (AmpConfig::get('auto_create') && $auth['success'] && !$user->username) { /* This is run if we want to autocreate users who don't exist (useful for non-mysql auth) */ $access = AmpConfig::get('auto_user') ? User::access_name_to_level(AmpConfig::get('auto_user')) : '5'; $name = $auth['name']; $email = $auth['email']; $website = $auth['website']; /* Attempt to create the user */ if (User::create($username, $name, $email, $website, hash('sha256', mt_rand()), $access)) { $user = User::get_from_username($username); } else { $auth['success'] = false; Error::add('general', T_('Unable to create local account')); } } // End if auto_create // This allows stealing passwords validated by external means // such as LDAP if (AmpConfig::get('auth_password_save') && $auth['success'] && isset($password)) { $user->update_password($password); } } /* If the authentication was a success */ if (isset($auth) && $auth['success'] && isset($user)) { // $auth->info are the fields specified in the config file // to retrieve for each user Session::create($auth); // Not sure if it was me or php tripping out,
/** * update_360051 * * Copy default .htaccess configurations */ public static function update_360051() { require_once AmpConfig::get('prefix') . '/lib/install.lib.php'; if (!install_check_server_apache()) { debug_event('update', 'Not using Apache, update 360051 skipped.', '5'); return true; } $htaccess_play_file = AmpConfig::get('prefix') . '/play/.htaccess'; $htaccess_rest_file = AmpConfig::get('prefix') . '/rest/.htaccess'; $htaccess_channel_file = AmpConfig::get('prefix') . '/channel/.htaccess'; $ret = true; if (!is_readable($htaccess_play_file)) { $created = false; if (check_htaccess_play_writable()) { if (!install_rewrite_rules($htaccess_play_file, AmpConfig::get('raw_web_path'), false)) { Error::add('general', T_('File copy error.')); } else { $created = true; } } if (!$created) { Error::add('general', T_('Cannot copy default .htaccess file.') . ' Please copy <b>' . $htaccess_play_file . '.dist</b> to <b>' . $htaccess_play_file . '</b>.'); $ret = false; } } if (!is_readable($htaccess_rest_file)) { $created = false; if (check_htaccess_rest_writable()) { if (!install_rewrite_rules($htaccess_rest_file, AmpConfig::get('raw_web_path'), false)) { Error::add('general', T_('File copy error.')); } else { $created = true; } } if (!$created) { Error::add('general', T_('Cannot copy default .htaccess file.') . ' Please copy <b>' . $htaccess_rest_file . '.dist</b> to <b>' . $htaccess_rest_file . '</b>.'); $ret = false; } } if (!is_readable($htaccess_channel_file)) { $created = false; if (check_htaccess_channel_writable()) { if (!install_rewrite_rules($htaccess_channel_file, AmpConfig::get('raw_web_path'), false)) { Error::add('general', T_('File copy error.')); } else { $created = true; } } if (!$created) { Error::add('general', T_('Cannot copy default .htaccess file.') . ' Please copy <b>' . $htaccess_channel_file . '.dist</b> to <b>' . $htaccess_channel_file . '</b>.'); $ret = false; } } return $ret; }
switch (AmpConfig::get('auto_user')) { case 'admin': $access = '100'; break; case 'user': $access = '25'; break; case 'guest': default: $access = '5'; break; } // auto-user level $new_user = User::create($username, $fullname, $email, $website, $pass1, $access, AmpConfig::get('admin_enable_required')); if (!$new_user) { Error::add('duplicate_user', T_("Error: Insert Failed")); require_once AmpConfig::get('prefix') . '/templates/show_user_registration.inc.php'; break; } if (!AmpConfig::get('admin_enable_required') && !AmpConfig::get('user_no_email_confirm')) { $client = new User($new_user); $validation = md5(uniqid(rand(), true)); $client->update_validation($validation); Registration::send_confirmation($username, $fullname, $email, $website, $pass1, $validation); } require_once AmpConfig::get('prefix') . '/templates/show_registration_confirmation.inc.php'; break; case 'show_add_user': default: require_once AmpConfig::get('prefix') . '/templates/show_user_registration.inc.php'; break;
/** * update_remote_catalog * * Pulls the data from a remote catalog and adds any missing songs to the * database. */ public function update_remote_catalog() { $songsadded = 0; try { $api = $this->createClient(); if ($api != null) { // Get all liked songs $songs = json_decode($api->get('me/favorites')); if ($songs) { foreach ($songs as $song) { if ($song->streamable == true && $song->kind == 'track') { $data = array(); $data['artist'] = $song->user->username; $data['album'] = $data['artist']; $data['title'] = $song->title; $data['year'] = $song->release_year; $data['mode'] = 'vbr'; $data['genre'] = explode(' ', $song->genre); $data['comment'] = $song->description; $data['file'] = $song->stream_url . '.mp3'; // Always stream as mp3, if evolve => $song->original_format; $data['size'] = $song->original_content_size; $data['time'] = intval($song->duration / 1000); if ($this->check_remote_song($data)) { debug_event('soundcloud_catalog', 'Skipping existing song ' . $data['file'], 5); } else { $data['catalog'] = $this->id; debug_event('soundcloud_catalog', 'Adding song ' . $data['file'], 5, 'ampache-catalog'); if (!Song::insert($data)) { debug_event('soundcloud_catalog', 'Insert failed for ' . $data['file'], 1); Error::add('general', T_('Unable to Insert Song - %s'), $data['file']); Error::display('general'); flush(); } else { $songsadded++; } } } } echo "<p>" . T_('Completed updating SoundCloud catalog(s).') . " " . $songsadded . " " . T_('Songs added.') . "</p><hr />\n"; flush(); // Update the last update value $this->update_last_update(); } else { echo "<p>" . T_('API Error: cannot get song list.') . "</p><hr />\n"; flush(); } } else { echo "<p>" . T_('API Error: cannot connect to SoundCloud.') . "</p><hr />\n"; flush(); } } catch (Exception $ex) { echo "<p>" . T_('SoundCloud exception: ') . $ex->getMessage() . "</p><hr />\n"; } return true; }
function mergeErrors($errorArray) { $e = new Error(); foreach ($errorArray as $_e) { if (db::isError($_e)) { $_error = $_e->_error; foreach ($_error as $es) { $e->add($es); } } } return $e; }
/** * create * * This creates a new catalog entry and associate it to current instance */ public static function create($data) { $name = $data['name']; $type = $data['type']; $rename_pattern = $data['rename_pattern']; $sort_pattern = $data['sort_pattern']; $insert_id = 0; $filename = AmpConfig::get('prefix') . '/modules/catalog/' . $type . '.catalog.php'; $include = (require_once $filename); if ($include) { $sql = 'INSERT INTO `catalog` (`name`, `catalog_type`, ' . '`rename_pattern`, `sort_pattern`) VALUES (?, ?, ?, ?)'; Dba::write($sql, array($name, $type, $rename_pattern, $sort_pattern)); $insert_id = Dba::insert_id(); if (!$insert_id) { Error::add('general', T_('Catalog Insert Failed check debug logs')); debug_event('catalog', 'Insert failed: ' . json_encode($data), 2); return false; } $classname = 'Catalog_' . $type; if (!$classname::create_type($insert_id, $data)) { $sql = 'DELETE FROM `catalog` WHERE `id` = ?'; Dba::write($sql, array($insert_id)); $insert_id = 0; } } return $insert_id; }
function update($postArray) { $db = new db(); $e = new Error(); if (User::isAdmin()) { $genreID = $db->sanitize_to_db($postArray['genreID']); if (!$this->isValidGenreID($postArray['genreID'])) { $e->add("Invalid genre specified"); } $name = $db->sanitize_to_db($postArray['name']); if ($name == '' || $name == null) { $e->add("You must specify a name for your band."); } $managerName = $db->sanitize_to_db($postArray['managerName']); $address1 = $db->sanitize_to_db($postArray['address1']); $address2 = $db->sanitize_to_db($postArray['address2']); $city = $db->sanitize_to_db($postArray['city']); $stateProvince = $db->sanitize_to_db($postArray['stateProvince']); if ($stateProvince == "??") { $stateProvince = $db->sanitize_to_db($postArray['stateProvinceOther']); } $postalCode = $db->sanitize_to_db($postArray['postalCode']); $bio = $db->sanitize_to_db($postArray['bio']); $miscellaneous = $db->sanitize_to_db($postArray['miscellaneous']); $country = $db->sanitize_to_db($postArray['country']); $defaultStateProvince = $db->sanitize_to_db($postArray['defaultStateProvince']); if ($defaultStateProvince == "??") { $defaultStateProvince = $db->sanitize_to_db($postArray['defaultStateProvince']); } $defaultCountry = $db->sanitize_to_db($postArray['defaultCountry']); $defaultCity = $db->sanitize_to_db($postArray['defaultCity']); $description = $db->sanitize_to_db($postArray['description']); if ($e->hasErrors()) { return $e; } $q = "delete from Band_Information"; $r = mysql_query($q); if (!$r) { return Error::MySQL(); } $q = "insert into Band_Information (name, managerName, address1, address2, city, stateProvince, postalCode, bio, miscellaneous, country, defaultStateProvince, defaultCountry, defaultCity, genreID, description) "; $q .= "values ('{$name}', '{$managerName}', '{$address1}', '{$address2}', '{$city}', '{$stateProvince}', '{$postalCode}', '{$bio}', '{$miscellaneous}', '{$country}', '{$defaultStateProvince}', '{$defaultCountry}', '{$defaultCity}', '{$genreID}', '{$description}')"; $r = mysql_query($q); // ping auditionrocks.com // aborted attempt at creating an audition directory /* include_class('xmlrpc'); $xc = new xmlrpc_client("/ping/", "www.auditionrocks.com"); $message = new xmlrpcmsg("audition.pingBack", array( new xmlrpcval($_SERVER["HTTP_HOST"] . SITE_WEB_DIRECTORY, "string"), new xmlrpcval($name, "string"), new xmlrpcval($bio, "string"), new xmlrpcval($genreID, "int"), new xmlrpcval($city, "string"), new xmlrpcval($stateProvince, "string"), new xmlrpcval($postalCode, "string"), new xmlrpcval($country, "string")) ); $response = $xc->send($message, 5, "POST"); */ if ($r) { return true; } else { return Error::create("An unexplained error occurred when trying to update your information."); } } }
if (!User::check_username($username)) { Error::add('username', T_('Error Username already exists')); } // Check the mail for correct address formation. if (!Mailer::validate_address($email)) { Error::add('email', T_('Invalid email address')); } /* If we've got an error then show add form! */ if (Error::occurred()) { require_once AmpConfig::get('prefix') . '/templates/show_add_user.inc.php'; break; } /* Attempt to create the user */ $user_id = User::create($username, $fullname, $email, $website, $pass1, $access, $state, $city); if (!$user_id) { Error::add('general', T_("Error: Insert Failed")); } $user = new User($user_id); $user->upload_avatar(); if ($access == 5) { $access = T_('Guest'); } elseif ($access == 25) { $access = T_('User'); } elseif ($access == 100) { $access = T_('Admin'); } /* HINT: %1 Username, %2 Access num */ show_confirmation(T_('New User Added'), sprintf(T_('%1$s has been created with an access level of %2$s'), $username, $access), AmpConfig::get('web_path') . '/admin/users.php'); break; case 'enable': $client = new User($_REQUEST['user_id']);
require_once 'lib/init.php'; $action = isset($_POST['action']) ? $_POST['action'] : ""; switch ($action) { case 'send': /* Check for posted email */ $result = false; if (isset($_POST['email']) && $_POST['email']) { /* Get the email address and the current ip*/ $email = scrub_in($_POST['email']); $current_ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; $result = send_newpassword($email, $current_ip); } if ($result) { Error::add('general', T_('Password has been sent')); } else { Error::add('general', T_('Password has not been sent')); } require AmpConfig::get('prefix') . '/templates/show_login_form.inc.php'; break; default: require AmpConfig::get('prefix') . '/templates/show_lostpassword_form.inc.php'; } function send_newpassword($email, $current_ip) { /* get the Client and set the new password */ $client = User::get_from_email($email); if ($client && $client->email == $email) { $newpassword = generate_password(6); $client->update_password($newpassword); $mailer = new Mailer(); $mailer->set_default_sender();
/** * install_create_account * this creates your initial account and sets up the preferences for the -1 user and you */ function install_create_account($username, $password, $password2) { if (!strlen($username) or !strlen($password)) { Error::add('general', T_('No Username/Password specified')); return false; } if ($password !== $password2) { Error::add('general', T_('Passwords do not match')); return false; } if (!Dba::check_database()) { Error::add('general', sprintf(T_('Database connection failed: %s'), Dba::error())); return false; } if (!Dba::check_database_inserted()) { Error::add('general', sprintf(T_('Database select failed: %s'), Dba::error())); return false; } $username = Dba::escape($username); $password = Dba::escape($password); $insert_id = User::create($username, 'Administrator', '', '', $password, '100'); if (!$insert_id) { Error::add('general', sprintf(T_('Administrative user creation failed: %s'), Dba::error())); return false; } // Fix the system users preferences User::fix_preferences('-1'); return true; }
/** * _clean_chunk * This is the clean function, its broken into * said chunks to try to save a little memory */ private function _clean_chunk($media_type, $chunk, $chunk_size) { debug_event('clean', "Starting chunk {$chunk}", 5); $dead = array(); $count = $chunk * $chunk_size; $sql = "SELECT `id`, `file` FROM `{$media_type}` " . "WHERE `catalog`='{$this->id}' LIMIT {$count},{$chunk_size}"; $db_results = Dba::read($sql); while ($results = Dba::fetch_assoc($db_results)) { debug_event('clean', 'Starting work on ' . $results['file'] . '(' . $results['id'] . ')', 5); $count++; if (UI::check_ticker()) { $file = str_replace(array('(', ')', '\''), '', $results['file']); UI::update_text('clean_count_' . $this->id, $count); UI::update_text('clean_dir_' . $this->id, scrub_out($file)); } $file_info = filesize($results['file']); if (!file_exists($results['file']) || $file_info < 1) { debug_event('clean', 'File not found or empty: ' . $results['file'], 5); Error::add('general', sprintf(T_('Error File Not Found or 0 Bytes: %s'), $results['file'])); // Store it in an array we'll delete it later... $dead[] = $results['id']; } else { if (!Core::is_readable(Core::conv_lc_file($results['file']))) { debug_event('clean', $results['file'] . ' is not readable, but does exist', 1); } } } return $dead; }
if (!Access::check('interface', '25')) { UI::access_denied(); exit; } if (!Core::form_verify('add_shout', 'post')) { UI::access_denied(); exit; } $shout_id = Shoutbox::create($_POST); header("Location:" . AmpConfig::get('web_path')); break; case 'show_add_shout': // Get our object first $object = Shoutbox::get_object($_REQUEST['type'], $_REQUEST['id']); if (!$object || !$object->id) { Error::add('general', T_('Invalid Object Selected')); Error::display('general'); break; } $object->format(); if (strtolower(get_class($object)) == 'song') { $data = $_REQUEST['offset']; } // Now go ahead and display the page where we let them add a comment etc require_once AmpConfig::get('prefix') . '/templates/show_add_shout.inc.php'; break; default: header("Location:" . AmpConfig::get('web_path')); break; } // end switch on action
/** * update_remote_catalog * * Pulls the data from a remote catalog and adds any missing songs to the * database. */ public function update_remote_catalog($type = 0) { set_time_limit(0); $remote_handle = $this->connect(); if (!$remote_handle) { return false; } // Get the song count, etc. $remote_catalog_info = $remote_handle->info(); // Tell 'em what we've found, Johnny! printf(T_('%u remote catalog(s) found (%u songs)'), $remote_catalog_info['catalogs'], $remote_catalog_info['songs']); flush(); // Hardcoded for now $step = 500; $current = 0; $total = $remote_catalog_info['songs']; while ($total > $current) { $start = $current; $current += $step; try { $songs = $remote_handle->send_command('songs', array('offset' => $start, 'limit' => $step)); } catch (Exception $e) { Error::add('general', $e->getMessage()); Error::display('general'); flush(); } // Iterate over the songs we retrieved and insert them foreach ($songs as $data) { if ($this->check_remote_song($data['song'])) { debug_event('remote_catalog', 'Skipping existing song ' . $data['song']['url'], 5); } else { $data['song']['catalog'] = $this->id; $data['song']['file'] = preg_replace('/ssid=.*?&/', '', $data['song']['url']); if (!Song::insert($data['song'])) { debug_event('remote_catalog', 'Insert failed for ' . $data['song']['self']['id'], 1); Error::add('general', T_('Unable to Insert Song - %s'), $data['song']['title']); Error::display('general'); flush(); } } } } // end while echo "<p>" . T_('Completed updating remote catalog(s).') . "</p><hr />\n"; flush(); // Update the last update value $this->update_last_update(); return true; }
break; case 'create_account': $results = parse_ini_file($configfile); AmpConfig::set_by_array($results, true); $password2 = scrub_in($_REQUEST['local_pass2']); if (!install_create_account($username, $password, $password2)) { require_once AmpConfig::get('prefix') . '/templates/show_install_account.inc.php'; break; } header("Location: " . $web_path . '/login.php'); break; case 'show_create_account': $results = parse_ini_file($configfile); /* Make sure we've got a valid config file */ if (!check_config_values($results)) { Error::add('general', T_('Error: Config file not found or unreadable')); require_once AmpConfig::get('prefix') . '/templates/show_install_config.inc.php'; break; } require_once AmpConfig::get('prefix') . '/templates/show_install_account.inc.php'; break; case 'init': require_once 'templates/show_install.inc.php'; break; case 'check': require_once 'templates/show_install_check.inc.php'; break; default: // Show the language options first require_once 'templates/show_install_lang.inc.php'; break;
/** * gather_folder * This returns the art from the folder of the files * If a limit is passed or the preferred filename is found the current * results set is returned */ public function gather_folder($limit = 5) { $media = new Album($this->uid); $songs = $media->get_songs(); $results = array(); $preferred = false; // For storing which directories we've already done $processed = array(); /* See if we are looking for a specific filename */ $preferred_filename = AmpConfig::get('album_art_preferred_filename'); // Array of valid extensions $image_extensions = array('bmp', 'gif', 'jp2', 'jpeg', 'jpg', 'png'); foreach ($songs as $song_id) { $song = new Song($song_id); $dir = dirname($song->file); if (isset($processed[$dir])) { continue; } debug_event('folder_art', "Opening {$dir} and checking for Album Art", 3); /* Open up the directory */ $handle = opendir($dir); if (!$handle) { Error::add('general', T_('Error: Unable to open') . ' ' . $dir); debug_event('folder_art', "Error: Unable to open {$dir} for album art read", 2); continue; } $processed[$dir] = true; // Recurse through this dir and create the files array while ($file = readdir($handle)) { $extension = pathinfo($file); $extension = $extension['extension']; // Make sure it looks like an image file if (!in_array($extension, $image_extensions)) { continue; } $full_filename = $dir . '/' . $file; // Make sure it's got something in it if (!filesize($full_filename)) { debug_event('folder_art', "Empty file, rejecting {$file}", 5); continue; } // Regularise for mime type if ($extension == 'jpg') { $extension = 'jpeg'; } // Take an md5sum so we don't show duplicate // files. $index = md5($full_filename); if ($file == $preferred_filename) { // We found the preferred filename and // so we're done. debug_event('folder_art', "Found preferred image file: {$file}", 5); $preferred[$index] = array('file' => $full_filename, 'mime' => 'image/' . $extension); break; } debug_event('folder_art', "Found image file: {$file}", 5); $results[$index] = array('file' => $full_filename, 'mime' => 'image/' . $extension); } // end while reading dir closedir($handle); } // end foreach songs if (is_array($preferred)) { // We found our favourite filename somewhere, so we need // to dump the other, less sexy ones. $results = $preferred; } debug_event('folder_art', 'Results: ' . json_encode($results), 5); if ($limit && count($results) > $limit) { $results = array_slice($results, 0, $limit); } return array_values($results); }
/** * create_type * * This creates a new catalog type entry for a catalog * It checks to make sure its parameters is not already used before creating * the catalog. */ public static function create_type($catalog_id, $data) { // TODO: This Method should be required / provided by parent $beetsdb = $data['beetsdb']; if (preg_match('/^[\\s]+$/', $beetsdb)) { Error::add('general', T_('Error: Beets selected, but no Beets DB File provided')); return false; } // Make sure this uri isn't already in use by an existing catalog $selectSql = 'SELECT `id` FROM `catalog_beets` WHERE `beetsdb` = ?'; $db_results = Dba::read($selectSql, array($beetsdb)); if (Dba::num_rows($db_results)) { debug_event('catalog', 'Cannot add catalog with duplicate uri ' . $beetsdb, 1); Error::add('general', sprintf(T_('Error: Catalog with %s already exists'), $beetsdb)); return false; } $insertSql = 'INSERT INTO `catalog_beets` (`beetsdb`, `catalog_id`) VALUES (?, ?)'; Dba::write($insertSql, array($beetsdb, $catalog_id)); return true; }
/** * handshake * * This is the function that handles verifying a new handshake * Takes a timestamp, auth key, and username. */ public static function handshake($input) { $timestamp = preg_replace('/[^0-9]/', '', $input['timestamp']); $passphrase = $input['auth']; if (empty($passphrase)) { $passphrase = $_POST['auth']; } $username = trim($input['user']); $ip = $_SERVER['REMOTE_ADDR']; $version = $input['version']; // Log the attempt debug_event('API', "Handshake Attempt, IP:{$ip} User:{$username} Version:{$version}", 5); // Version check shouldn't be soo restrictive... only check with initial version to not break clients compatibility if (intval($version) < self::$auth_version) { debug_event('API', 'Login Failed: version too old', 1); Error::add('api', T_('Login Failed: version too old')); return false; } $user_id = -1; // Grab the correct userid if (!$username) { $client = User::get_from_apikey($passphrase); if ($client) { $user_id = $client->id; } } else { $client = User::get_from_username($username); $user_id = $client->id; } // Log this attempt debug_event('API', "Login Attempt, IP:{$ip} Time: {$timestamp} User:{$username} ({$user_id}) Auth:{$passphrase}", 1); if ($user_id > 0 && Access::check_network('api', $user_id, 5, $ip)) { // Authentication with user/password, we still need to check the password if ($username) { // If the timestamp isn't within 30 minutes sucks to be them if ($timestamp < time() - 1800 || $timestamp > time() + 1800) { debug_event('API', 'Login Failed: timestamp out of range ' . $timestamp . '/' . time(), 1); Error::add('api', T_('Login Failed: timestamp out of range')); return false; } // Now we're sure that there is an ACL line that matches // this user or ALL USERS, pull the user's password and // then see what we come out with $realpwd = $client->get_password(); if (!$realpwd) { debug_event('API', 'Unable to find user with userid of ' . $user_id, 1); Error::add('api', T_('Invalid Username/Password')); return false; } $sha1pass = hash('sha256', $timestamp . $realpwd); if ($sha1pass !== $passphrase) { $client = null; } } else { $timestamp = time(); } if ($client) { // Create the session $data = array(); $data['username'] = $client->username; $data['type'] = 'api'; $data['value'] = $timestamp; $token = Session::create($data); debug_event('API', 'Login Success, passphrase matched', 1); // We need to also get the 'last update' of the // catalog information in an RFC 2822 Format $sql = 'SELECT MAX(`last_update`) AS `update`, MAX(`last_add`) AS `add`, MAX(`last_clean`) AS `clean` FROM `catalog`'; $db_results = Dba::read($sql); $row = Dba::fetch_assoc($db_results); // Now we need to quickly get the song totals $sql = 'SELECT COUNT(`id`) AS `song`, ' . 'COUNT(DISTINCT(`album`)) AS `album`, ' . 'COUNT(DISTINCT(`artist`)) AS `artist` ' . 'FROM `song`'; $db_results = Dba::read($sql); $counts = Dba::fetch_assoc($db_results); // Next the video counts $sql = "SELECT COUNT(`id`) AS `video` FROM `video`"; $db_results = Dba::read($sql); $vcounts = Dba::fetch_assoc($db_results); $sql = "SELECT COUNT(`id`) AS `playlist` FROM `playlist`"; $db_results = Dba::read($sql); $playlist = Dba::fetch_assoc($db_results); $sql = "SELECT COUNT(`id`) AS `catalog` FROM `catalog` WHERE `catalog_type`='local'"; $db_results = Dba::read($sql); $catalog = Dba::fetch_assoc($db_results); echo XML_Data::keyed_array(array('auth' => $token, 'api' => self::$version, 'session_expire' => date("c", time() + AmpConfig::get('session_length') - 60), 'update' => date("c", $row['update']), 'add' => date("c", $row['add']), 'clean' => date("c", $row['clean']), 'songs' => $counts['song'], 'albums' => $counts['album'], 'artists' => $counts['artist'], 'playlists' => $playlist['playlist'], 'videos' => $vcounts['video'], 'catalogs' => $catalog['catalog'])); return true; } // match } // end while debug_event('API', 'Login Failed, unable to match passphrase', '1'); XML_Data::error('401', T_('Error Invalid Handshake - ') . T_('Invalid Username/Password')); }
function add($postArray) { $db = new db(); include_class('venues'); $e = new Error(); $name = $db->sanitize_to_db($postArray['name']); $dt = $db->sanitize_to_db($postArray['date']); $date = date("Y-m-d", strtotime($dt)); if ($postArray['time']) { $time = $db->sanitize_to_db($postArray['time']); $time = "'" . date("H:i:s", strtotime($time)) . "'"; } else { $time = "null"; } if ($postArray['cost'] != "") { $cost = $db->sanitize_to_db($postArray['cost']); $cost = "'{$cost}'"; } else { $cost = "null"; } $is_all_ages = $postArray['is_all_ages'] == '1' ? 1 : 0; $other_bands = $db->sanitize_to_db($postArray['other_bands']); $notes = $db->sanitize_to_db($postArray['notes']); if (User::isAdmin()) { $uo = User::get($postArray['user_id']); if (db::isError($uo)) { $e->add($uo); } else { if (!$uo->isAdmin() && $uo->isBandMember()) { $e->add("Invalid user. User must be a band member or an administrator."); } } } else { $uo = User::getCurrent(); } if ($postArray['venue_id'] != '0') { $ve = Venue::get($postArray['venue_id']); } if (db::isError($ve)) { $e->add($ve); } if ($e->hasErrors()) { return $e; } $user_id = $uo->getID(); $venue_id = $db->sanitize_to_db($postArray['venue_id']); if (!$name) { $name = is_object($ve) && !db::isError($ve) ? $db->sanitize_to_db($ve->getName()) : "(untitled show)"; } $r = mysql_query("insert into Shows (name, venue_id, date, time, user_id, cost, is_all_ages, other_bands, notes, is_active) values ('{$name}', '{$venue_id}', '{$date}', {$time}, {$user_id}, {$cost}, {$is_all_ages}, '{$other_bands}', '{$notes}'," . DEFAULT_ACTIVE . ")"); if ($r) { return Show::get(mysql_insert_id()); } else { return Error::MySQL(); } }
/** * create * This is a static function that takes a key'd array for input * and if everything is good creates the object. */ public static function create(array $data) { // Make sure we've got a name if (!strlen($data['name'])) { Error::add('name', T_('Name Required')); } $allowed_array = array('https', 'http', 'mms', 'mmsh', 'mmsu', 'mmst', 'rtsp', 'rtmp'); $elements = explode(":", $data['url']); if (!in_array($elements['0'], $allowed_array)) { Error::add('url', T_('Invalid URL must be http:// or https://')); } // Make sure it's a real catalog $catalog = Catalog::create_from_id($data['catalog']); if (!$catalog->name) { Error::add('catalog', T_('Invalid Catalog')); } if (Error::occurred()) { return false; } // If we've made it this far everything must be ok... I hope $sql = "INSERT INTO `live_stream` (`name`,`site_url`,`url`,`catalog`,`codec`) " . "VALUES (?, ?, ?, ?, ?)"; $db_results = Dba::write($sql, array($data['name'], $data['site_url'], $data['url'], $catalog->id, $data['codec'])); return $db_results; }
/** * update * This function is an all encompasing update function that * calls the mini ones does all the error checking and all that * good stuff */ public function update(array $data) { if (empty($data['username'])) { Error::add('username', T_('Error Username Required')); } if ($data['password1'] != $data['password2'] and !empty($data['password1'])) { Error::add('password', T_("Error Passwords don't match")); } if (Error::occurred()) { return false; } if (!isset($data['fullname_public'])) { $data['fullname_public'] = false; } foreach ($data as $name => $value) { if ($name == 'password1') { $name = 'password'; } else { $value = scrub_in($value); } switch ($name) { case 'password': case 'access': case 'email': case 'username': case 'fullname': case 'fullname_public': case 'website': case 'state': case 'city': if ($this->{$name} != $value) { $function = 'update_' . $name; $this->{$function}($value); } break; case 'clear_stats': Stats::clear($this->id); break; default: // Rien a faire break; } } return $this->id; }
function remove() { $e = new Error(); if (User::isAdmin()) { if (!@mysql_query("delete from Users where ID = " . $this->ID)) { $e->add(mysql_error()); return $e; } else { return true; } } else { $e->add('You may not remove this user.'); return $e; } }
} } } // end if add // Now check for an update if ($_REQUEST['update_path'] != '/' and strlen($_REQUEST['update_path'])) { if ($catalog_id = Catalog_local::get_from_path($_REQUEST['update_path'])) { $songs = Song::get_from_path($_REQUEST['update_path']); foreach ($songs as $song_id) { Catalog::update_single_item('song', $song_id); } } } // end if update if ($catalog_id <= 0) { Error::add('general', T_("This subdirectory is not part of an existing catalog. Update cannot be processed.")); } break; case 'add_catalog': $catalog_id = intval($_REQUEST['catalog_id']); $catalog = Catalog::create_from_id($catalog_id); if ($catalog !== null) { // Run our initial add $catalog->add_to_catalog($options); if (!defined('SSE_OUTPUT')) { Error::display('catalog_add'); } } break; case 'gather_media_art': $catalogs = $_REQUEST['catalogs'] ? $_REQUEST['catalogs'] : Catalog::get_catalogs();
/** * create * * This takes a keyed array of data and trys to insert it as a * new ACL entry */ public static function create($data) { if (!self::_verify_range($data['start'], $data['end'])) { return false; } // Check existing ACLs to make sure we're not duplicating values here if (self::exists($data)) { debug_event('ACL Create', 'Error: An ACL equal to the created one already exists. Not adding another one: ' . $data['start'] . ' - ' . $data['end'], 1); Error::add('general', T_('Duplicate ACL defined')); return false; } $start = @inet_pton($data['start']); $end = @inet_pton($data['end']); $name = $data['name']; $user = $data['user'] ?: '-1'; $level = intval($data['level']); $type = self::validate_type($data['type']); $enabled = make_bool($data['enabled']) ? 1 : 0; $sql = 'INSERT INTO `access_list` (`name`, `level`, `start`, `end`, ' . '`user`,`type`,`enabled`) VALUES (?, ?, ?, ?, ?, ?, ?)'; Dba::write($sql, array($name, $level, $start, $end, $user, $type, $enabled)); return true; }
function update($postArray) { $db = new db(); $e = new Error(); $firstname = $db->sanitize_to_db($postArray['firstname']); if (!$firstname) { $e->add("A guest performer entry must contain a first name."); } $lastname = $db->sanitize_to_db($postArray['lastname']); $function = $db->sanitize_to_db($postArray['function']); if (!$function) { $e->add("A guest performer must serve a function."); } $description = $db->sanitize_to_db($postArray['description']); $website = $db->sanitize_to_db($postArray['website']); if ($e->hasErrors()) { return $e; } if (User::isAdmin()) { $r = @mysql_query("update Band_Guest_Performers set firstname='{$firstname}', lastname='{$lastname}', function='{$function}', description='{$description}', website='{$website}' where ID = {$this->ID}"); if (!$r) { return Error::MySQL(); } else { return $this; } } else { return Error::create("Only an administrator may update guest performers."); } }
/** * * borra o rompe el enlace con las tablas dependientes * @param integer $id * @return boolean */ protected function _delete_or_nullify_dependents($id) { //verifyng dependencies if (!empty($this->dependents) and $id != 0) { foreach ($this->has_many as $model) { $model1 = Camelize($model); //$dependentObject = new $model1(); $children = $this->{$model1}->Find(array('conditions' => Singulars($this->_TableName()) . "_id='" . $id . "'")); foreach ($children as $child) { switch ($this->dependents) { case 'destroy': if (!$child->Delete()) { $this->_error->add(array('field' => $this->_TableName(), 'message' => "Cannot delete dependents")); return FALSE; } break; case 'nullify': $child->{$this->_TableName() . '_id'} = ''; if (!$child->Save()) { $this->_error->add(array('field' => $this->_TableName(), 'message' => "Cannot nullify dependents")); return FALSE; } break; } } } } return true; }
function getPhotoAreaObject() { if ($this->photo_area_id > 0) { $ma = MediaArea::get($this->photo_area_id); return $ma; } else { $e = new Error(); $e->add("An administrator has not yet registered this tour for photos."); return $e; } }