Ejemplo n.º 1
0
 private function myFileDeleteTest($guid, $collection, $expectedHTTPStatus = "200", $expectedXMLElements, $expectedXMLAttributes)
 {
     $url = $this->service_url . "/" . $guid;
     $curl = curl_init($url);
     $curl_post_data = array("collection" => $collection, "test" => "test", "test2" => "test2");
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     // return the result on success
     curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
     // set post fields
     curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/xml"));
     // set accept header
     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
     $curl_response = curl_exec($curl);
     $headers = curl_getinfo($curl);
     curl_close($curl);
     // print_r($headers);
     //echo $curl_response;
     // validate result
     if ($curl_response == true) {
         $xml = SmintTestUtils::validateXMLResponse($headers, $curl_response, "200", array("track_to_be_deleted"), array("collection", "id"), $this);
         MyLog::printWithDuration("Successfully added with the result: " . str_replace("\n", "", $curl_response));
     } else {
         echo __METHOD__ . "\n";
         echo "curl_response:" . $curl_response . "\n";
         print_r($headers);
         print_r($curl_post_data);
         $this->fail("There was a problem accessing the api! \n\n");
     }
 }
Ejemplo n.º 2
0
 protected function download()
 {
     $filename = $this->fileURL;
     $this->localFile = null;
     if (file_exists($filename)) {
         // local file
         $this->localFile = $this->fileURL;
     } else {
         // might be remote file
         // try to download
         // check if remote location exists
         if (RestUtils::url_exists($this->fileURL)) {
             $tmpName = tempnam(sys_get_temp_dir(), 'smafe_');
             $tmpFilename = $tmpName . '_' . basename($this->fileURL);
             $success = copy($this->fileURL, $tmpFilename);
             if ($success) {
                 $this->localFile = $tmpFilename;
                 //log the file download and create a local urlinfo file
                 MyLog::printWithDuration("Downloaded URL: {$this->fileURL} to Local File: {$this->localFile}");
                 $handle = fopen($tmpName, "w");
                 fwrite($handle, "local     : {$this->localFile}\n");
                 fwrite($handle, "url       : {$this->fileURL}\n");
                 fwrite($handle, "ext key   : {$this->external_key}\n");
                 fwrite($handle, "collection: {$this->collection}\n");
                 fclose($handle);
             }
         }
     }
 }
Ejemplo n.º 3
0
 protected function fetch($j)
 {
     $k = curl_exec($this->curl);
     $l = curl_error($this->curl);
     $m = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
     $j[0]["code"] = $m;
     if ($l) {
         MyLog::checkLogError($l, "curl", $j);
     }
     $n = MyLog::microtime_float() - $this->start_generate_time;
     $this->start_generate_time = MyLog::microtime_float();
     MyLog::checkLogSlow($n, "curl", $j);
     return $k;
 }
 private function myQueryTest($trackextkey, $collectionname = null, $expectedHTTPStatus = "200", $expectedXMLElements, $expectedXMLAttributes)
 {
     $config = TestConfig::getConfig();
     $service_url = $config['server']['baseurl'] . '/track_external_key/';
     $url = $service_url . $trackextkey;
     if (!is_null($collectionname) && strlen($collectionname) > 0) {
         $url = $url . "?collection=" . urlencode($collectionname);
     }
     $curl = curl_init($url);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/xml"));
     $curl_response = curl_exec($curl);
     $headers = curl_getinfo($curl);
     curl_close($curl);
     if ($curl_response == true) {
         $xml = SmintTestUtils::validateXMLResponse($headers, $curl_response, $expectedHTTPStatus, $expectedXMLElements, $expectedXMLAttributes, $this);
         MyLog::printWithDuration("Expected: {$expectedHTTPStatus} - queried with the result: " . str_replace("\n", "", $curl_response));
     } else {
         echo __METHOD__ . "\n";
         echo "curl_response:" . $curl_response . "\n";
         print_r($headers);
         $this->fail("There was a problem accessing the api! \n\n");
     }
 }
Ejemplo n.º 5
0
 public function actionloginAffiliate()
 {
     if (isset($_GET["opauth"])) {
         try {
             $opauth_code = $_GET["opauth"];
             $response = unserialize(base64_decode($opauth_code));
             // Check if it's an error callback
             if (array_key_exists('error', $response) or !isset($response['auth'])) {
                 MyLog::Error('Error get info!');
                 $this->redirect('/');
             }
             $auth = $response['auth'];
             // Check if auth is missing info
             if (!isset($auth['provider']) or !isset($auth['uid']) or !isset($auth['info'])) {
                 MyLog::Error('Cannot get auth info!');
                 $this->redirect('/');
             }
             if (!in_array($auth['provider'], array('Facebook', 'Twitter', 'LinkedIn', 'Google', 'Orcid'))) {
                 MyLog::Error('Provider is not supported!');
                 $this->redirect('/');
             }
             $user = User::processAffiliateUser($auth);
             #process to mark as logined in
             $_SESSION['affiliate_login']['provider'] = $auth['provider'];
             $_SESSION['affiliate_login']['uid'] = $auth['uid'];
             #use useridentity to login
             $model = new LoginForm();
             $model->username = $auth['uid'];
             $model->password = $auth['uid'];
             #validate user input and redirect to the previous page if valid
             if ($model->validate()) {
                 $this->redirect(Yii::app()->user->returnUrl);
             } else {
                 Yii::log("FAILED VALIDATION: " . print_r($model->getErrors(), true), "error");
             }
         } catch (Exception $e) {
             MyLog::error(print_r($e, true));
             exit;
         }
     } else {
         $this->redirect('/');
     }
 }
Ejemplo n.º 6
0
<?php

// init logger
$mylog = MyLog::singleton(MyLog::getLevel("ALL"), "test.log");
// define the autoloader to load classes from the lib folder
function __autoload($className)
{
    if (in_array($className, array("TestConfig", "SmintTestUtils"))) {
        $filename = dirname(__FILE__) . '/' . $className . '.php';
    } else {
        $filename = dirname(__FILE__) . '/../../lib/' . $className . '.php';
    }
    if (file_exists($filename)) {
        require $filename;
    } else {
        throw new Exception('Class "' . $className . '" could not be autoloaded. File not found: ' . $filename);
    }
}
Ejemplo n.º 7
0
 /**
  * Запускает распаковку дампа на удаленном сервере
  *
  * @return bool
  */
 protected function execDump()
 {
     $res = $this->_request('execDump');
     if (!intval($res)) {
         MyLog::warning($res);
         return false;
     }
     if (intval($res) != $this->_itemForExport) {
         MyLog::warning('Для обновления было отправлено ' . $this->_itemForExport . ' записей, обновлено ' . intval($res) . ' записей');
         return false;
     }
     return true;
 }
Ejemplo n.º 8
0
Archivo: Track.php Proyecto: EQ4/smafe
 protected function openDistanceJobs($addfilejobid, $fvtid, $disttid)
 {
     $sqlquery = "select count(*) as opendistjobs from distancejob dj where dj.smafejob_addfile_id = :smafejob_addfile_id and dj.featurevectortype_id = :featurevectortype_id and dj.distancetype_id = :distancetype_id;";
     $dbconnection = $this->dbconnection;
     // prepare statement
     $stmt = $dbconnection->prepare($sqlquery);
     // bind paramters
     $stmt->bindParam(':smafejob_addfile_id', $addfilejobid, PDO::PARAM_INT);
     $stmt->bindParam(':featurevectortype_id', $fvtid, PDO::PARAM_INT);
     $stmt->bindParam(':distancetype_id', $disttid, PDO::PARAM_INT);
     // execute query
     $querysuccess = $stmt->execute();
     if ($querysuccess) {
         // fetch the results
         $queryresult = $stmt->fetchAll();
         if ($queryresult[0][0] > 0) {
             $result = true;
         } else {
             $result = false;
         }
     } else {
         // assume that there are no open tasks if the query was unsuccessful
         $result = false;
     }
     MyLog::printWithDuration("Query openDistanceJobs {$addfilejobid}  {$fvtid} {$disttid} " . $queryresult[0][0]);
     return $result;
 }
Ejemplo n.º 9
0
 /**
  * Function to test adding of URLs
  *
  * @param string $file_url the URL 
  * @param string $ext_key the external Key; if empty string no ext_key will be set 
  * @param string $collection the collection name; if empty string no collection will be set 
  * @param string $expectedHTTPStatus the statuscode of the expected result 
  * @param string $expectedXMLElements an array containing all expected elements of the returned xml 
  * @param string $expectedXMLAttributes an array containing all expected attributes of the returned xml 
  * @return void
  * @author jochum
  */
 private function myFileAddTest($file_url, $ext_key, $collection, $expectedHTTPStatus = "200", $expectedXMLElements, $expectedXMLAttributes)
 {
     $service_url = $this->config['server']['baseurl'] . '/track/add/';
     # build post options
     $curl_post_data = array();
     if (file_exists($file_url)) {
         # file is local
         $curl_post_data["file"] = $file_url;
     } else {
         # assume it is remote
         $curl_post_data["url"] = $file_url;
     }
     if (is_string($ext_key) && strlen($ext_key) > 0) {
         $curl_post_data["external_key"] = $ext_key;
     }
     if (is_string($collection) && strlen($collection) > 0) {
         $curl_post_data["collection"] = $collection;
     }
     # build curl request
     $curl = curl_init($service_url);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     // return the result on success
     curl_setopt($curl, CURLOPT_POST, true);
     // set post
     curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
     // set post fields
     curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/xml"));
     // set accept header
     $curl_response = curl_exec($curl);
     $headers = curl_getinfo($curl);
     curl_close($curl);
     if ($curl_response == true) {
         $xml = SmintTestUtils::validateXMLResponse($headers, $curl_response, $expectedHTTPStatus, $expectedXMLElements, $expectedXMLAttributes, $this);
         MyLog::printWithDuration("Successfully added with the result: " . str_replace("\n", "", $curl_response));
     } else {
         echo __METHOD__ . "\n";
         echo "curl_response:" . $curl_response . "\n";
         echo "headers:\n";
         print_r($headers);
         echo "curl_post_data:\n";
         print_r($curl_post_data);
         $this->fail("There was a problem accessing the api! \n\n");
     }
 }
Ejemplo n.º 10
0
 protected function liveQuery()
 {
     $livehost = $this->apiConfig["liveapi"]["livehost"];
     $liveport = $this->apiConfig["liveapi"]["liveport"];
     $liveclient = $this->apiConfig["liveapi"]["liveclient"];
     $assumedmaxdist = $this->apiConfig["liveapi"]["assumedmaxdist"];
     // build command
     $command = "{$liveclient} --live --no-daemon --liveport={$liveport} --livehost={$livehost} --livefile=" . escapeshellarg($this->localFile) . "";
     MyLog::printWithDuration("Command: {$command}");
     $return_var = 0;
     $aOutput = array();
     // passthru ($command);
     exec($command, $aOutput, $return_var);
     if ($return_var == 0) {
         MyLog::printWithDuration(implode(" - ", $aOutput));
         //echo "$output";
         //print_r($aOutput);
         $this->nns = array();
         $c = 0;
         // counter
         $limit = $this->count;
         // array of distance values to normalize
         //$aDistancevalues = array();
         foreach ($aOutput as $line) {
             //echo "$line ";
             // only if we have a line with numbers (excludes the first line with headings)
             $a = explode(',', $line);
             if (is_numeric($a[0])) {
                 // get URL and add it to array
                 array_push($a, $this->getURLFromTrack_id($a[0]));
                 // add the record to master array
                 array_push($this->nns, $a);
                 //array_push($aDistancevalues, $a[2]);
                 $c++;
                 if ($c >= $limit) {
                     break;
                 }
             }
         }
         // normalize distance values between 1 and 0
         //$maxDist = max($aDistancevalues);
         for ($i = 0; $i < count($this->nns); $i++) {
             //		$this->nns[$i][2] = 1 - $this->nns[$i][2] / $assumedmaxdist;
             $this->nns[$i][2] = max(array(1 - $this->nns[$i][2] / $assumedmaxdist, 0));
         }
         /* now, $this->nns contains something like
         	
             [0] => Array
                 (
                     [0] => 149
                     [1] => -1
                     [2] => 0.909733
                     [3] => /home/ewald/tmp/reference_tracks/409601_My Beat_Sumo Acapella.mp3
                 )
         
             [1] => Array
                 (
                     [0] => 153
                     [1] => -1
                     [2] => 0.896527166667
                     [3] => /home/ewald/tmp/reference_tracks/499135_Finally_Acapella.mp3
                 )
         
             [2] => Array
                 (
                     [0] => 136
                     [1] => -1
                     [2] => 0.885311833333
                     [3] => /home/ewald/tmp/reference_tracks/289156_Vazilando_Acapella.mp3
                 )
         
         
         	...
         	*/
         //	print_r($this->nns);
         //phpinfo();
         $this->response->setStatus(200);
     } else {
         $this->response->setStatus(500);
         $this->errorMessage = "Client exit code = {$return_var}. Details are logged.";
         MyLog::printWithDuration(implode(" - ", $aOutput));
     }
 }
Ejemplo n.º 11
0
 /**
  * Fetch
  *
  * Execute the curl object
  *
  * @return StdClass
  * @access protected
  * @throws ApiException
  */
 protected function fetch($debug_backtrace)
 {
     $raw_response = curl_exec($this->curl);
     $error = curl_error($this->curl);
     $code = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
     $debug_backtrace[0]["code"] = $code;
     if ($error) {
         //bat dau ghi log loi vao file
         MyLog::checkLogError($error, "curl", $debug_backtrace);
     }
     //curl_close($this->curl);
     //bat dau tinh thoi gian xu ly
     $time_request = MyLog::microtime_float() - $this->start_generate_time;
     //sau day tiep tuc gan lai thoi gian de xu ly tiep
     $this->start_generate_time = MyLog::microtime_float();
     //kiem tra xem time request co bi slow qua ko
     MyLog::checkLogSlow($time_request, "curl", $debug_backtrace);
     return $raw_response;
 }
Ejemplo n.º 12
0
<?php

$responceContentType = "text/html";
try {
    // set config file
    $CONFIGFILENAME = "../config/smintapi.ini";
    // bootstrap the API
    // defines autoloader
    // creates logger
    require_once "../lib/bootstrapapi.php";
    MyLog::printWithDuration("Starting Request: " . RestUtils::getFullUrl($_SERVER));
    // search for Class to handle request
    $apiClass = RestUtils::getApiMethod($_SERVER, $apiConfig["known_api_methods"]);
    // hande Request depending on apiClass
    if (strlen($apiClass) > 0) {
        // only if a class was identified
        try {
            class_exists($apiClass);
            $service = new $apiClass();
            $service->handleRawRequest($_SERVER, $_GET, $_POST);
            MyLog::printWithDuration("Finished Request: " . RestUtils::getFullUrl($_SERVER));
        } catch (Exception $e) {
            // catch error if the class was not found
            RestUtils::sendResponse(404, $e->getMessage(), $responceContentType);
        }
    } else {
        RestUtils::sendResponse(404);
    }
} catch (Exception $e) {
    RestUtils::sendResponse(500, $e->getMessage(), $responceContentType);
}
Ejemplo n.º 13
0
Archivo: MyLog.php Proyecto: EQ4/smafe
 /**
  * prints message and time until last message
  *
  * @param string $debugMessage the Message to be logged
  * @param string $messageLogLevel the Log level of the message, the message will only be logged if the Logger was instantiated with a higher or equal log level 
  * @return void
  * @author jochum
  */
 public static function printWithDuration($debugMessage, $messageLogLevel = 10000)
 {
     $logger = MyLog::singleton();
     if ($messageLogLevel >= $logger->logLevel) {
         $fullMessage = RestUtils::getRealIpAddr() . " - " . date("[d/M/Y:G:i:s]") . " " . $debugMessage . " - took (ms): " . (microtime(true) - $logger->starttime) * 1000 . "\n";
         $logger->writeToFile($fullMessage);
         $logger->starttime = microtime(true);
     }
 }
Ejemplo n.º 14
0
<?php

// I expect $CONFIGFILENAME to be set, otherwise bail out
if (isset($CONFIGFILENAME)) {
    $apiConfig = SmintapiConfig::initConfig($CONFIGFILENAME);
    $apiConfig = SmintapiConfig::getConfig();
} else {
    throw new Exception('Please set $CONFIGFILENAME to the config file to be used.');
}
// init logger with log level defined in the config file
$mylog = MyLog::singleton($apiConfig["logging"]["logLevel"]);
// define the autoloader to load classes from the lib folder
function __autoload($className)
{
    $filename = dirname(__FILE__) . '/../lib/' . $className . '.php';
    if (file_exists($filename)) {
        require $filename;
    } else {
        throw new Exception('Class "' . $className . '" could not be autoloaded. File not found: ' . $filename);
    }
}
function stripslashes_deep($value)
{
    $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    return $value;
}