public static function logRequestFlat($context, $request) { $logMessage = "request parameters: ;"; $parameters = $request->getParameterHolder()->getAll(); $logMessage = $logMessage . smintTools::implode_with_key($parameters, ";", ";"); self::log($context, $logMessage); }
public static function implode_with_key_4js($assoc) { return '{' . smintTools::implode_with_key($assoc, ": '", "',") . '\'}'; }
/** This is executed when searched for related tracks and metadata */ public function executeRelatedtrack(sfWebRequest $request) { $this->getContext()->getConfiguration()->loadHelpers('Url'); $empty_metadatafilteredquery = false; $distances = NULL; $files = NULL; // get request parameters $metadataquery = $request->getParameter('metadataquery'); $tracknr = $request->getParameter('tracknr'); $limit = $request->getParameter('limit', $this->getContext()->getConfiguration()->getSmintMaxQueryResults()); $offset = $request->getParameter('offset', 0); $id_prefix = $request->getParameter('id_prefix', '') . smintTools::generateHtmlId($tracknr) . "_"; $omit_empty_metadataquery = $request->getParameter('omit_empty_metadataquery', false); $distancetypeid = sfConfig::get('app_defaults_distancetypeid', 0); $featurevectortypeid = sfConfig::get('app_defaults_featurevectortypeid', 0); mysfLog::logRequest($this, $request); //get file via external key $file = FilePeer::getFileByExternalKey($tracknr); //only if the file was found in the smafestore db if ($file) { // run query $fileTrackId = $file->getTrackid(); $relatedCriteria = $this->buildRelatedQuery($fileTrackId, $featurevectortypeid, $distancetypeid, $limit, $offset, $metadataquery); $related = FilePeer::doSelect($relatedCriteria); // if omit empty metadataquery is true if ($omit_empty_metadataquery) { if (count($related) > 0) { // if the query returned results $distances = DistancePeer::doSelect($relatedCriteria); } else { // if the query returned no results -> retry without metadata $empty_metadatafilteredquery = true; $relatedCriteria = $this->buildRelatedQuery($fileTrackId, $featurevectortypeid, $distancetypeid, $limit, $offset); $related = FilePeer::doSelect($relatedCriteria); $distances = DistancePeer::doSelect($relatedCriteria); } } else { $distances = DistancePeer::doSelect($relatedCriteria); } } $files = FiledescPeer::doSelect($relatedCriteria); // add duration // $fileDownloadURL = url_for("getAudioFile/download") . "?tracknr=" . rawurlencode($tracknr); $queryFileMetadata = FiledescPeer::retrieveByPk($tracknr); $fileInfoName = $queryFileMetadata->getTitle() . " - " . $queryFileMetadata->getPerformers(); $uploadedFilePHPUrl_incomplete = url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($tracknr); $uploadedFileURL = smintUploadFileHelper::getDirectFileUrl($file->getUri()); return $this->renderPartial('search/result', array('render' => 'related', 'uploadedFilePHPUrl_incomplete' => $uploadedFilePHPUrl_incomplete, 'uploadedFileURL' => $uploadedFileURL, 'seedLabel' => $fileInfoName, 'id_prefix' => $id_prefix, 'tracknr' => $tracknr, 'files' => $files, 'distances' => $distances, 'limit' => $limit, 'offset' => $offset, 'metadataquery' => $metadataquery, 'empty_metadatafilteredquery' => $empty_metadatafilteredquery, 'aSegmSearch' => $aSegmSearch)); }
<?php } ?> <!-- search similar functions --> <?php foreach ($files as $i => $file) { ?> <?php $currentid = smintTools::generateHtmlId($file->getTracknr()); ?> <?php $smintRequestParameters = array(); ?> <?php $smintRequestParameters['tracknr'] = $file->getTracknr(); ?> <?php $smintRequestParameters['metadataquery'] = $metadataquery; ?> <?php //$relatedUrlsmint = url_for('search/relatedtrack').'?'.http_build_query($smintRequestParameters) $relatedUrlsmint = url_for('search/related') . '?' . http_build_query($smintRequestParameters); ?>
/** Performs live query with Smafe * Also tries to start the server if it seems to be down. In this case, an exception is thrown with explanation * @param $filepath The file to query (local file path) * @param $aSegmSearch Associative array with data about segmented search * @param $autostart if true, the server is tried to started if it seems to be down. Default = true */ public static function queryFile($filepath, $aSegmSearch, $autorestart = true) { // The command $exec_command; if ($aSegmSearch['enabled']) { // segmented search $command = mysfConfig::get('app_live_settings_command_segmentedsearch', ""); $command = str_replace('$LIVEFILE', $filepath, $command); $command = str_replace('$BEGINTIME', smintTools::convertTimeMsToMM_SS_HH($aSegmSearch['startSegment']), $command); $command = str_replace('$ENDTIME', smintTools::convertTimeMsToMM_SS_HH($aSegmSearch['endSegment']), $command); $exec_command = $command; } else { // normal search $command = mysfConfig::get('app_live_settings_command', ""); $command = str_replace('$LIVEFILE', $filepath, $command); $exec_command = $command; } $exec_output = array(); $exec_err = array(); mysfLog::log(self::$context, "INFO - executing live query: {$exec_command}"); exec($exec_command, $exec_output, $exec_result); if ($exec_result != 0) { if ($autorestart) { // try to start server try { mysfLog::log(self::$context, "INFO: Server seems not to be running. STARTING the SERVER."); self::restartServer($aSegmSearch['enabled']); throw new Exception("Server was restarted. Try again in a few minutes. Log: " . print_r($exec_output, true)); } catch (Exception $e) { // restart failed mysfLog::log(self::$context, "STARTING the SERVER failed: " . $e->getMessage()); throw new Exception($e->getMessage()); } } else { // do not start the smafedistd server but return error message $result_array = array("command" => $exec_command, "result" => $exec_result, "error" => $exec_output); $error_message = "ERROR during live query. " . print_r($result_array, true); mysfLog::log(self::$context, $error_message); throw new Exception($error_message); } } $result_array = array("output" => $exec_output, "result" => $exec_result); return $result_array; }
/** provides the file as download/streaming * Request params: * - tracknr * - fileid * - uploaded * ( either tracknr or fileid or uploaded is required) * - format optional. One of: mp3, ogg. If format is given, the file is converted to the given format, using command line invocations that are configured in app.yml * * */ public function executeDownload(sfWebRequest $request) { // write session, so it won't lock other requests session_write_close(); $reqparamUploaded = $this->getRequestParameter('uploaded'); if ($reqparamUploaded) { $filename = smintUploadFileHelper::getUploadPath() . $reqparamUploaded; } else { $tracknr = $this->getRequestParameter('tracknr'); if ($tracknr) { $file = FilePeer::getFileByExternalKey($tracknr); $filekey = $tracknr; } else { # check if file.id is given $fileid = $this->getRequestParameter('fileid'); $file = FilePeer::retrieveByPK($fileid); $filekey = $fileid; } //check if a file was found matching tracknr, else exit with 404 if ($file) { $filename = $file->getUri(); } else { $this->forward404("file not found in database."); } } //check if a tracknr is given, otherwise exit with 404 if (!$filename) { $this->forward404("Invalid query! Provide tracknr, fileid or uploaded to get a file."); } if (file_exists($filename)) { //check if file is inside the folder configured in smint/config/app.yml // or inside the upload folder $mp3Path = dirname(sfConfig::get('app_files_mp3path') . "/file"); if (strpos($filename, $mp3Path) === false && strpos($filename, smintUploadFileHelper::getUploadPath()) === false) { $this->forward404("file: {$filename} is outside of the configured path (app.yml): {$mp3Path}. Accessing files outside the path is not allowed. Check app.yml and URI in file table."); } // ----------------------------------------------- // -------------- check for format -------------- // if no format is given, $reqparamFormat = $this->getRequestParameter('format'); if ($reqparamFormat) { if (substr($filename, -3) === $reqparamFormat) { mysfLog::log($this, "INFO: format parameter equals original audio file suffix. No conversion."); if ($reqparamFormat === "mp3") { $contenttype = "audio/mpeg"; } else { $contenttype = "audio/{$reqparamFormat}"; } } else { // conversion if ($reqparamFormat === "ogg") { $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat); $contenttype = "audio/ogg"; } else { if ($reqparamFormat === "mp3") { $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat); $contenttype = "audio/mpeg"; } else { if ($reqparamFormat === "waveform") { $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat); $contenttype = "application/txt"; } else { if ($reqparamFormat === "png") { $waveformfilename = smintFileserverHelper::doFileConversion($filename, "waveform"); $wfdata = split(", ", file_get_contents($waveformfilename)); //mysfLog::log($this, print_r($wfdata, true)); // how much detail we want. Larger number means less detail // (basically, how many bytes/frames to skip processing) // the lower the number means longer processing time // EP: in SMINT we do not chagne this. To change the detail, edit your waveform_resolution // config param in app.yml! define("DETAIL", 1); // get user vars from form $width = $this->getRequestParameter('width') ? rawurldecode($this->getRequestParameter('width')) : 640; $height = $this->getRequestParameter('height') ? rawurldecode($this->getRequestParameter('height')) : 100; $foreground = $this->getRequestParameter('fg') ? rawurldecode($this->getRequestParameter('fg')) : "#4D4D4D"; $background = $this->getRequestParameter('bg') ? rawurldecode($this->getRequestParameter('bg')) : "#ffffff"; $maxval = 0; $factor = sfConfig::get('app_defaults_waveform_factor', 0.8); // create original image width based on amount of detail $img = imagecreatetruecolor(sizeof($wfdata) / DETAIL, $height); // apply factor to the data //$wfdata_factor = array_map("this->pow_func", $wfdata); for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) { $wfdata[$i] = pow(abs($wfdata[$i]), $factor); } $datamaxval = max(array_map("abs", $wfdata)); $normconstant = doubleval($height) / doubleval($datamaxval); for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) { $wfdata[$i] = $wfdata[$i] * $normconstant; } /* for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) { if (abs($wfdata[$i]) > $maxval) { $maxval = $wfdata[$i]; } } if ($maxval < 40) { for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) { $wfdata[$i] = pow(abs($wfdata[$i]), 1.4); } } * */ // fill background of image if ($background == "") { imagesavealpha($img, true); $transparentColor = imagecolorallocatealpha($img, 0, 0, 0, 127); imagefill($img, 0, 0, $transparentColor); } else { list($r, $g, $b) = smintTools::html2rgb($background); imagefilledrectangle($img, 0, 0, sizeof($wfdata) / DETAIL, $height, imagecolorallocate($img, $r, $g, $b)); } // generate foreground color list($r, $g, $b) = smintTools::html2rgb($foreground); // loop through frames/bytes of wav data as genearted above for ($d = 0; $d < sizeof($wfdata); $d += DETAIL) { // relative value based on height of image being generated // data values can range between -127 and 128 $v = $wfdata[$d]; //$v = pow($v, sfConfig::get('app_defaults_waveform_factor', 0.8)); // draw the line on the image using the $v value and centering it vertically on the canvas imageline($img, $d / DETAIL, ($height - $v) / 2, $d / DETAIL, ($height + $v) / 2, imagecolorallocate($img, $r, $g, $b)); } // want it resized? if ($width != imagesx($img)) { // resample the image to the proportions defined in the form $rimg = imagecreatetruecolor($width, $height); // save alpha from original image imagesavealpha($rimg, true); imagealphablending($rimg, false); // copy to resized imagecopyresampled($rimg, $img, 0, 0, 0, 0, $width, $height, sizeof($wfdata) / DETAIL, $height); $img = $rimg; } $contenttype = "image/png"; header("Content-type: {$contenttype}"); imagepng($img); imagedestroy($img); // dont render view return sfView::NONE; } else { $error_message = "ERROR: Format {$reqparamFormat} not valid"; mysfLog::log($this, $error_message); throw new Exception($error_message); } } } } } } else { mysfLog::log($this, "INFO: format parameter not given, sending the original file "); // assuming file ending as content type. Just an approximation $contenttype = "audio/" . substr($filename, -3); } // do a redirect to file to have apache handle it $this->redirect(smintUploadFileHelper::getDirectFileUrl_for_uploads($filename)); /* alternate version of redirect (not using symf framework) * does not work better :-( * $url = smintUploadFileHelper::getDirectFileUrl_for_uploads($filename); $statusCode = 302; // redirect $response = $this->context->getResponse(); $response->clearHttpHeaders(); $response->setStatusCode($statusCode); $response->setHttpHeader('Location', $url); $response->send(); throw new sfStopException(); // we do not reach this part b/o the redirect! * */ // ------------ delegate to helper for download // serves file, obeying the range header smintFileserverHelper::serve_file_resumable($this->getResponse(), $filename, $contenttype); // dont render view return sfView::NONE; //return sfView::HEADER_ONLY; } else { $missingfile = $filename ? $filename : "No filename found!"; $this->forward404("file for tracknr: not found: " . $missingfile); } }
/** Returns appropriate JS code for Smintplayer embedding for Seed song. * <p>Note: this function returns more code that the counterpart "getMp3PlayerConfig" * @param $uploadedFilePHPUrl_incomplete incomplete download url for file. format can be appended * @param $uploadedFileURL url of original file uploaded (curretnly used as mp3 although this might not be true) * */ public static function getMp3PlayerConfig4Seedsong($uploadedFilePHPUrl_incomplete, $uploadedFileURL) { //needed for javascript_tag use_helper('JavascriptBase'); $player = sfConfig::get('app_mp3player_defaultplayer', 'worldpress'); switch ($player) { case 'flash-mp3-player': return 'not implemented'; break; case 'worldpress': return 'not implemented'; break; case 'smintplayer': default: if (smintTools::endsWith($uploadedFileURL, "mp3")) { $audiofile_mp3 = $uploadedFileURL; $audiofile_ogg = $uploadedFilePHPUrl_incomplete . "&format=ogg"; $orig_ext_comma = ""; $setmedia_orig_part = ""; } elseif (smintTools::endsWith($uploadedFileURL, "ogg")) { $audiofile_mp3 = $uploadedFilePHPUrl_incomplete . "&format=mp3"; $audiofile_ogg = $uploadedFileURL; $orig_ext_comma = ""; $setmedia_orig_part = ""; } else { $audiofile_mp3 = $uploadedFilePHPUrl_incomplete . "&format=mp3"; $audiofile_ogg = $uploadedFilePHPUrl_incomplete . "&format=ogg"; $audiofile_orig = $uploadedFileURL; $orig_ext = smintTools::getExtension($uploadedFileURL); $orig_ext_comma = "{$orig_ext},"; $setmedia_orig_part = "{$orig_ext}: \$('#jquery_jplayer_2').jPlayer('option', 'playlist')[0].audiofile_orig,"; } // get configuration $playerConfig = sfConfig::get('app_mp3player_smintplayer'); // build options array of array. First dimension is list of files, second is assoc array with values for the player $options = array(); if (!isset($aSegmSearch['enabled'])) { $aSegmSearch['enabled'] = false; } $protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0; $hostname = $_SERVER['SERVER_ADDR']; $port = $_SERVER['SERVER_PORT']; $server = $protocol . $hostname . ":" . $port; $tmparray = array('text' => '', 'audiofile_mp3' => $audiofile_mp3, 'audiofile_ogg' => $audiofile_ogg, 'audiofile_orig' => isset($audiofile_orig) && $audiofile_orig ? $audiofile_orig : "not used", 'waveformimage' => $uploadedFilePHPUrl_incomplete . "&format=png", 'duration' => '', 'segments' => $aSegmSearch['enabled'] ? $aSegmSearch['resultsegments'][$i] : array()); // we cannot put all these fields into one array since the output format must be like // , A: XXXX, B: XXX // and not //, {A: XXXX, B: XXX} $options[] = $tmparray; $playlist_part = ", playlist: " . smintTools::my_options_for_javascript($options) . ", waveform_resolution: " . intval(sfConfig::get('app_defaults_waveform_resolution')) . ', waveform_factor: ' . doubleval(sfConfig::get('app_defaults_waveform_factor')); $general_part = "\n\t\t\t\tready: function () {\n\t\t\t\t\t\$(this).jPlayer('setMedia', {\n\t\t\t\t\t\t{$setmedia_orig_part}\n\t\t\t\t\t\tmp3: \$('#jquery_jplayer_2').jPlayer('option', 'playlist')[0].audiofile_mp3,\n\t\t\t\t\t\toga: \$('#jquery_jplayer_2').jPlayer('option', 'playlist')[0].audiofile_ogg\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tplay: function() { // To avoid both jPlayers playing together.\n\t\t\t\t\t\$(this).jPlayer('pauseOthers');\n\t\t\t\t},\n\t\t\t\tswfPath: ' " . _compute_public_path('', 'smintplayer/js', '', false) . "' ,\n\t\t\t\tsupplied: '{$orig_ext_comma} mp3, oga',\n\t\t\t\tsolution: 'flash, html', \n\t\t\t\tcssSelectorAncestor: '#jp_container_2',\n\t\t\t\twmode: 'window',\n\t\t\t\tpreload: 'auto'\n\t\t\t\t" . $playlist_part; return $general_part; break; } }