Example #1
0
    public function uploader()
    {
        $payload = base64_encode(serialize($this->args('payload')));
        $this->setArg('label');
        //where you want me go?
        $redirect = "http://" . SITE_HOSTNAME . "/upload/success/{$payload}";
        $acl = "public-read";
        $expiration = gmdate("Y-m-d\\TH:i:s\\Z", strtotime("+1 day"));
        //create amazons crazy policy data array.
        $policy_json = '
			{
				"expiration": "' . $expiration . '",
				"conditions": [
					{"acl": "' . $acl . '"},
					{"bucket": "' . AMAZON_S3_BUCKET_NAME . '"},
					["starts-with", "$key", "uploads/"],
					["starts-with", "$Content-Type", ""],
					["starts-with", "$Content-Disposition", ""],
					{"success_action_redirect": "' . $redirect . '"},
					["content-length-range", 1, 262144000]
				]
			}';
        //create our various encoded/signed stuff.
        $policy_json_cleaned = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $policy_json);
        $policy_encoded = base64_encode($policy_json_cleaned);
        $signature = hex2b64(hash_hmac('sha1', $policy_encoded, AMAZON_AWS_SECRET));
        //okay, set our view vars.
        $this->set('redirect', $redirect);
        $this->set('acl', $acl);
        $this->set('policy', $policy_encoded);
        $this->set('signature', $signature);
    }
Example #2
0
 function addSOAPHeader($function)
 {
     $timestamp = date("d/m/Y H:i:s");
     $stringToSign = $function . $timestamp;
     $signature = hex2b64($this->hasher->hash($stringToSign));
     $header = new SOAP_Header("securityHeader", NULL, array('paccesskey' => $this->accessKey, 'timestamp' => $timestamp, "signature" => $signature, "action" => $function));
     $this->soapClient->addHeader($header);
 }
Example #3
0
function sign_s3_url_path($schema, $endpoint, $bucketName, $objectName)
{
    $schema = 'https';
    $keyId = getenv('AWS_ACCESS_KEY_ID');
    $secretKey = getenv('AWS_SECRET_ACCESS_KEY');
    $S3_URL = "{$schema}://s3{$endpoint}.amazonaws.com/{$bucketName}/";
    $expires = time() + getenv('S3_SIGNED_URL_EXPIRY');
    $objectName = url_normalize($objectName);
    $stringToSign = "GET\n\n\n{$expires}\n/{$bucketName}/{$objectName}";
    $sig = urlencode(hex2b64(hash_hmac("sha1", $stringToSign, $secretKey)));
    return "{$S3_URL}{$objectName}?AWSAccessKeyId={$keyId}&Expires={$expires}&Signature={$sig}";
}
function remove_acl($file_key)
{
    //first get the current acl policy (to grab owner info)
    //the date and time in rfc 822 (again)
    $rfc_822_datetime = date("r");
    //assemble your s3 signature
    $s3_signature = "GET\n\n\n" . $rfc_822_datetime . "\n/" . BUCKET_NAME . "/" . $file_key . "?acl";
    $hasher =& new Crypt_HMAC(S3_SECRET_KEY, "sha1");
    $signature = hex2b64($hasher->hash($s3_signature));
    //make the request to get current acl
    $s3req =& new HTTP_Request(S3_URL . BUCKET_NAME . "/" . $file_key . "?acl");
    $s3req->setMethod('GET');
    $s3req->addHeader("Date", $rfc_822_datetime);
    $s3req->addHeader("Authorization", "AWS " . S3_ACCESS_KEY . ":" . $signature);
    $s3req->sendRequest();
    $current_acl = $s3req->getResponseBody();
    //seperate out the "group" policy
    $split_policy = split('<Grant><Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">', $current_acl);
    //create the new policy with just owner info (preserved part of original policy)
    $new_policy = $split_policy[0] . "</AccessControlList></AccessControlPolicy>";
    //ok, now construct another request to set the new policy
    //the date and time in rfc 822 (again)
    $rfc_822_datetime = date("r");
    //assemble your s3 signature
    $s3_signature = "PUT\n\napplication/x-www-form-urlencoded\n" . $rfc_822_datetime . "\n/" . BUCKET_NAME . "/" . $file_key . "?acl";
    $hasher =& new Crypt_HMAC(S3_SECRET_KEY, "sha1");
    $signature = hex2b64($hasher->hash($s3_signature));
    //make the request to change the acl
    $s3req =& new HTTP_Request(S3_URL . BUCKET_NAME . "/" . $file_key . "?acl");
    $s3req->setMethod('PUT');
    $s3req->addHeader("Date", $rfc_822_datetime);
    $s3req->addHeader("Authorization", "AWS " . S3_ACCESS_KEY . ":" . $signature);
    //new xml acl
    $s3req->setBody($new_policy);
    $s3req->sendRequest();
    if ($s3req->getResponseCode() != 200) {
        echo "Problem updating acl for " . $file_key . " - Status was " . $s3req->getResponseCode() . "\n";
    }
}
function get_hash($file_key)
{
    print $file_key;
    //the date and time in rfc 822 (again)
    $rfc_822_datetime = date("r");
    //assemble your s3 signature
    $s3_signature = "GET\n\n\n" . $rfc_822_datetime . "\n/" . BUCKET_NAME . "/" . $file_key;
    $hasher =& new Crypt_HMAC(S3_SECRET_KEY, "sha1");
    $signature = hex2b64($hasher->hash($s3_signature));
    //make the request
    $s3req =& new HTTP_Request(S3_URL . BUCKET_NAME . "/" . $file_key);
    $s3req->setMethod('GET');
    $s3req->addHeader("Date", $rfc_822_datetime);
    $s3req->addHeader("Authorization", "AWS " . S3_ACCESS_KEY . ":" . $signature);
    $s3req->sendRequest();
    //create the temporary file
    $handle = fopen(PROJECT_DIR . "imgtmp/needshash.gif", "a+");
    fwrite($handle, $s3req->getResponseBody());
    fclose($handle);
    //get the hash, delete the file, and return the hash
    $hash = md5_file(PROJECT_DIR . "imgtmp/needshash.gif");
    unlink(PROJECT_DIR . "imgtmp/needshash.gif");
    return $hash;
}
Example #6
0
 function doModel()
 {
     osc_run_hook('before_search');
     if (osc_rewrite_enabled()) {
         // IF rewrite is not enabled, skip this part, preg_match is always time&resources consuming task
         $p_sParams = "/" . Params::getParam('sParams', false, false);
         if (preg_match_all('|\\/([^,]+),([^\\/]*)|', $p_sParams, $m)) {
             $l = count($m[0]);
             for ($k = 0; $k < $l; $k++) {
                 switch ($m[1][$k]) {
                     case osc_get_preference('rewrite_search_country'):
                         $m[1][$k] = 'sCountry';
                         break;
                     case osc_get_preference('rewrite_search_region'):
                         $m[1][$k] = 'sRegion';
                         break;
                     case osc_get_preference('rewrite_search_city'):
                         $m[1][$k] = 'sCity';
                         break;
                     case osc_get_preference('rewrite_search_city_area'):
                         $m[1][$k] = 'sCityArea';
                         break;
                     case osc_get_preference('rewrite_search_category'):
                         $m[1][$k] = 'sCategory';
                         break;
                     case osc_get_preference('rewrite_search_user'):
                         $m[1][$k] = 'sUser';
                         break;
                     case osc_get_preference('rewrite_search_pattern'):
                         $m[1][$k] = 'sPattern';
                         break;
                     default:
                         // custom fields
                         if (preg_match("/meta(\\d+)-?(.*)?/", $m[1][$k], $results)) {
                             $meta_key = $m[1][$k];
                             $meta_value = $m[2][$k];
                             $array_r = array();
                             if (Params::existParam('meta')) {
                                 $array_r = Params::getParam('meta');
                             }
                             if ($results[2] == '') {
                                 // meta[meta_id] = meta_value
                                 $meta_key = $results[1];
                                 $array_r[$meta_key] = $meta_value;
                             } else {
                                 // meta[meta_id][meta_key] = meta_value
                                 $meta_key = $results[1];
                                 $meta_key2 = $results[2];
                                 $array_r[$meta_key][$meta_key2] = $meta_value;
                             }
                             $m[1][$k] = 'meta';
                             $m[2][$k] = $array_r;
                         }
                         break;
                 }
                 Params::setParam($m[1][$k], $m[2][$k]);
             }
             Params::unsetParam('sParams');
         }
     }
     $uriParams = Params::getParamsAsArray();
     $searchUri = osc_search_url($uriParams);
     if ($this->uri != 'feed') {
         if (str_replace("%20", '+', $searchUri) != str_replace("%20", '+', WEB_PATH . $this->uri)) {
             $this->redirectTo($searchUri, 301);
         }
     }
     ////////////////////////////////
     //GETTING AND FIXING SENT DATA//
     ////////////////////////////////
     $p_sCategory = Params::getParam('sCategory');
     if (!is_array($p_sCategory)) {
         if ($p_sCategory == '') {
             $p_sCategory = array();
         } else {
             $p_sCategory = explode(",", $p_sCategory);
         }
     }
     $p_sCityArea = Params::getParam('sCityArea');
     if (!is_array($p_sCityArea)) {
         if ($p_sCityArea == '') {
             $p_sCityArea = array();
         } else {
             $p_sCityArea = explode(",", $p_sCityArea);
         }
     }
     $p_sCity = Params::getParam('sCity');
     if (!is_array($p_sCity)) {
         if ($p_sCity == '') {
             $p_sCity = array();
         } else {
             $p_sCity = explode(",", $p_sCity);
         }
     }
     $p_sRegion = Params::getParam('sRegion');
     if (!is_array($p_sRegion)) {
         if ($p_sRegion == '') {
             $p_sRegion = array();
         } else {
             $p_sRegion = explode(",", $p_sRegion);
         }
     }
     $p_sCountry = Params::getParam('sCountry');
     if (!is_array($p_sCountry)) {
         if ($p_sCountry == '') {
             $p_sCountry = array();
         } else {
             $p_sCountry = explode(",", $p_sCountry);
         }
     }
     $p_sUser = Params::getParam('sUser');
     if (!is_array($p_sUser)) {
         if ($p_sUser == '') {
             $p_sUser = '';
         } else {
             $p_sUser = explode(",", $p_sUser);
         }
     }
     $p_sLocale = Params::getParam('sLocale');
     if (!is_array($p_sLocale)) {
         if ($p_sLocale == '') {
             $p_sLocale = '';
         } else {
             $p_sLocale = explode(",", $p_sLocale);
         }
     }
     $p_sPattern = trim(strip_tags(Params::getParam('sPattern')));
     // ADD TO THE LIST OF LAST SEARCHES
     if (osc_save_latest_searches() && (!Params::existParam('iPage') || Params::getParam('iPage') == 1)) {
         $savePattern = osc_apply_filter('save_latest_searches_pattern', $p_sPattern);
         if ($savePattern != '') {
             LatestSearches::newInstance()->insert(array('s_search' => $savePattern, 'd_date' => date('Y-m-d H:i:s')));
         }
     }
     $p_bPic = Params::getParam('bPic');
     $p_bPic = $p_bPic == 1 ? 1 : 0;
     $p_bPremium = Params::getParam('bPremium');
     $p_bPremium = $p_bPremium == 1 ? 1 : 0;
     $p_sPriceMin = Params::getParam('sPriceMin');
     $p_sPriceMax = Params::getParam('sPriceMax');
     //WE CAN ONLY USE THE FIELDS RETURNED BY Search::getAllowedColumnsForSorting()
     $p_sOrder = Params::getParam('sOrder');
     if (!in_array($p_sOrder, Search::getAllowedColumnsForSorting())) {
         $p_sOrder = osc_default_order_field_at_search();
     }
     $old_order = $p_sOrder;
     //ONLY 0 ( => 'asc' ), 1 ( => 'desc' ) AS ALLOWED VALUES
     $p_iOrderType = Params::getParam('iOrderType');
     $allowedTypesForSorting = Search::getAllowedTypesForSorting();
     $orderType = osc_default_order_type_at_search();
     foreach ($allowedTypesForSorting as $k => $v) {
         if ($p_iOrderType == $v) {
             $orderType = $k;
             break;
         }
     }
     $p_iOrderType = $orderType;
     $p_sFeed = Params::getParam('sFeed');
     $p_iPage = 0;
     if (is_numeric(Params::getParam('iPage')) && Params::getParam('iPage') > 0) {
         $p_iPage = intval(Params::getParam('iPage')) - 1;
     }
     if ($p_sFeed != '') {
         $p_sPageSize = 1000;
     }
     $p_sShowAs = Params::getParam('sShowAs');
     $aValidShowAsValues = array('list', 'gallery');
     if (!in_array($p_sShowAs, $aValidShowAsValues)) {
         $p_sShowAs = osc_default_show_as_at_search();
     }
     // search results: it's blocked with the maxResultsPerPage@search defined in t_preferences
     $p_iPageSize = intval(Params::getParam('iPagesize'));
     if ($p_iPageSize > 0) {
         if ($p_iPageSize > osc_max_results_per_page_at_search()) {
             $p_iPageSize = osc_max_results_per_page_at_search();
         }
     } else {
         $p_iPageSize = osc_default_results_per_page_at_search();
     }
     //FILTERING CATEGORY
     $bAllCategoriesChecked = false;
     $successCat = false;
     if (count($p_sCategory) > 0) {
         foreach ($p_sCategory as $category) {
             $successCat = $this->mSearch->addCategory($category) || $successCat;
         }
     } else {
         $bAllCategoriesChecked = true;
     }
     //FILTERING CITY_AREA
     foreach ($p_sCityArea as $city_area) {
         $this->mSearch->addCityArea($city_area);
     }
     $p_sCityArea = implode(", ", $p_sCityArea);
     //FILTERING CITY
     foreach ($p_sCity as $city) {
         $this->mSearch->addCity($city);
     }
     $p_sCity = implode(", ", $p_sCity);
     //FILTERING REGION
     foreach ($p_sRegion as $region) {
         $this->mSearch->addRegion($region);
     }
     $p_sRegion = implode(", ", $p_sRegion);
     //FILTERING COUNTRY
     foreach ($p_sCountry as $country) {
         $this->mSearch->addCountry($country);
     }
     $p_sCountry = implode(", ", $p_sCountry);
     // FILTERING PATTERN
     if ($p_sPattern != '') {
         $this->mSearch->addPattern($p_sPattern);
         $osc_request['sPattern'] = $p_sPattern;
     } else {
         // hardcoded - if there isn't a search pattern, order by dt_pub_date desc
         if ($p_sOrder == 'relevance') {
             $p_sOrder = 'dt_pub_date';
             foreach ($allowedTypesForSorting as $k => $v) {
                 if ($p_iOrderType == 'desc') {
                     $orderType = $k;
                     break;
                 }
             }
             $p_iOrderType = $orderType;
         }
     }
     // FILTERING USER
     if ($p_sUser != '') {
         $this->mSearch->fromUser($p_sUser);
     }
     // FILTERING LOCALE
     $this->mSearch->addLocale($p_sLocale);
     // FILTERING IF WE ONLY WANT ITEMS WITH PICS
     if ($p_bPic) {
         $this->mSearch->withPicture(true);
     }
     // FILTERING IF WE ONLY WANT PREMIUM ITEMS
     if ($p_bPremium) {
         $this->mSearch->onlyPremium(true);
     }
     //FILTERING BY RANGE PRICE
     $this->mSearch->priceRange($p_sPriceMin, $p_sPriceMax);
     //ORDERING THE SEARCH RESULTS
     $this->mSearch->order($p_sOrder, $allowedTypesForSorting[$p_iOrderType]);
     //SET PAGE
     if ($p_sFeed == 'rss') {
         // If param sFeed=rss, just output last 'osc_num_rss_items()'
         $this->mSearch->page(0, osc_num_rss_items());
     } else {
         $this->mSearch->page($p_iPage, $p_iPageSize);
     }
     // CUSTOM FIELDS
     $custom_fields = Params::getParam('meta');
     $fields = Field::newInstance()->findIDSearchableByCategories($p_sCategory);
     $table = DB_TABLE_PREFIX . 't_item_meta';
     if (is_array($custom_fields)) {
         foreach ($custom_fields as $key => $aux) {
             if (in_array($key, $fields)) {
                 $field = Field::newInstance()->findByPrimaryKey($key);
                 switch ($field['e_type']) {
                     case 'TEXTAREA':
                     case 'TEXT':
                     case 'URL':
                         if ($aux != '') {
                             $aux = "%{$aux}%";
                             $sql = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $str_escaped = Search::newInstance()->dao->escape($aux);
                             $sql .= $table . '.fk_i_field_id = ' . $key . ' AND ';
                             $sql .= $table . ".s_value LIKE " . $str_escaped;
                             $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')');
                         }
                         break;
                     case 'DROPDOWN':
                     case 'RADIO':
                         if ($aux != '') {
                             $sql = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $str_escaped = Search::newInstance()->dao->escape($aux);
                             $sql .= $table . '.fk_i_field_id = ' . $key . ' AND ';
                             $sql .= $table . ".s_value = " . $str_escaped;
                             $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')');
                         }
                         break;
                     case 'CHECKBOX':
                         if ($aux != '') {
                             $sql = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $sql .= $table . '.fk_i_field_id = ' . $key . ' AND ';
                             $sql .= $table . ".s_value = 1";
                             $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')');
                         }
                         break;
                     case 'DATE':
                         if ($aux != '') {
                             $y = (int) date('Y', $aux);
                             $m = (int) date('n', $aux);
                             $d = (int) date('j', $aux);
                             $start = mktime('0', '0', '0', $m, $d, $y);
                             $end = mktime('23', '59', '59', $m, $d, $y);
                             $sql = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $sql .= $table . '.fk_i_field_id = ' . $key . ' AND ';
                             $sql .= $table . ".s_value >= " . $start . " AND ";
                             $sql .= $table . ".s_value <= " . $end;
                             $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')');
                         }
                         break;
                     case 'DATEINTERVAL':
                         if (is_array($aux) && (!empty($aux['from']) && !empty($aux['to']))) {
                             $from = $aux['from'];
                             $to = $aux['to'];
                             $start = $from;
                             $end = $to;
                             $sql = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $sql .= $table . '.fk_i_field_id = ' . $key . ' AND ';
                             $sql .= $start . " >= " . $table . ".s_value AND s_multi = 'from'";
                             $sql1 = "SELECT fk_i_item_id FROM {$table} WHERE ";
                             $sql1 .= $table . ".fk_i_field_id = " . $key . " AND ";
                             $sql1 .= $end . " <= " . $table . ".s_value AND s_multi = 'to'";
                             $sql_interval = "select a.fk_i_item_id from (" . $sql . ") a where a.fk_i_item_id IN (" . $sql1 . ")";
                             $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql_interval . ')');
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
     }
     osc_run_hook('search_conditions', Params::getParamsAsArray());
     // RETRIEVE ITEMS AND TOTAL
     $key = md5(osc_base_url() . $this->mSearch->toJson());
     $found = null;
     $cache = osc_cache_get($key, $found);
     $aItems = null;
     $iTotalItems = null;
     if ($cache) {
         $aItems = $cache['aItems'];
         $iTotalItems = $cache['iTotalItems'];
     } else {
         $aItems = $this->mSearch->doSearch();
         $iTotalItems = $this->mSearch->count();
         $_cache['aItems'] = $aItems;
         $_cache['iTotalItems'] = $iTotalItems;
         osc_cache_set($key, $_cache, OSC_CACHE_TTL);
     }
     $iStart = $p_iPage * $p_iPageSize;
     $iEnd = min(($p_iPage + 1) * $p_iPageSize, $iTotalItems);
     $iNumPages = ceil($iTotalItems / $p_iPageSize);
     // works with cache enabled ?
     osc_run_hook('search', $this->mSearch);
     //preparing variables...
     $countryName = $p_sCountry;
     if (strlen($p_sCountry) == 2) {
         $c = Country::newInstance()->findByCode($p_sCountry);
         if ($c) {
             $countryName = $c['s_name'];
         }
     }
     $regionName = $p_sRegion;
     if (is_numeric($p_sRegion)) {
         $r = Region::newInstance()->findByPrimaryKey($p_sRegion);
         if ($r) {
             $regionName = $r['s_name'];
         }
     }
     $cityName = $p_sCity;
     if (is_numeric($p_sCity)) {
         $c = City::newInstance()->findByPrimaryKey($p_sCity);
         if ($c) {
             $cityName = $c['s_name'];
         }
     }
     $this->_exportVariableToView('search_start', $iStart);
     $this->_exportVariableToView('search_end', $iEnd);
     $this->_exportVariableToView('search_category', $p_sCategory);
     // hardcoded - non pattern and order by relevance
     $p_sOrder = $old_order;
     $this->_exportVariableToView('search_order_type', $p_iOrderType);
     $this->_exportVariableToView('search_order', $p_sOrder);
     $this->_exportVariableToView('search_pattern', $p_sPattern);
     $this->_exportVariableToView('search_from_user', $p_sUser);
     $this->_exportVariableToView('search_total_pages', $iNumPages);
     $this->_exportVariableToView('search_page', $p_iPage);
     $this->_exportVariableToView('search_has_pic', $p_bPic);
     $this->_exportVariableToView('search_only_premium', $p_bPremium);
     $this->_exportVariableToView('search_country', $countryName);
     $this->_exportVariableToView('search_region', $regionName);
     $this->_exportVariableToView('search_city', $cityName);
     $this->_exportVariableToView('search_price_min', $p_sPriceMin);
     $this->_exportVariableToView('search_price_max', $p_sPriceMax);
     $this->_exportVariableToView('search_total_items', $iTotalItems);
     $this->_exportVariableToView('items', $aItems);
     $this->_exportVariableToView('search_show_as', $p_sShowAs);
     $this->_exportVariableToView('search', $this->mSearch);
     // json
     $json = $this->mSearch->toJson();
     $encoded_alert = base64_encode(osc_encrypt_alert($json));
     // Create the HMAC signature and convert the resulting hex hash into base64
     $stringToSign = osc_get_alert_public_key() . $encoded_alert;
     $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign));
     $server_signature = Session::newInstance()->_set('alert_signature', $signature);
     $this->_exportVariableToView('search_alert', $encoded_alert);
     // calling the view...
     if (count($aItems) === 0) {
         header('HTTP/1.1 404 Not Found');
     }
     osc_run_hook("after_search");
     if (!Params::existParam('sFeed')) {
         $this->doView('search.php');
     } else {
         if ($p_sFeed == '' || $p_sFeed == 'rss') {
             // FEED REQUESTED!
             header('Content-type: text/xml; charset=utf-8');
             $feed = new RSSFeed();
             $feed->setTitle(__('Latest listings added') . ' - ' . osc_page_title());
             $feed->setLink(osc_base_url());
             $feed->setDescription(__('Latest listings added in') . ' ' . osc_page_title());
             if (osc_count_items() > 0) {
                 while (osc_has_items()) {
                     if (osc_count_item_resources() > 0) {
                         osc_has_item_resources();
                         $feed->addItem(array('title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8"), 'description' => osc_item_description(), 'country' => osc_item_country(), 'region' => osc_item_region(), 'city' => osc_item_city(), 'city_area' => osc_item_city_area(), 'category' => osc_item_category(), 'dt_pub_date' => osc_item_pub_date(), 'image' => array('url' => htmlentities(osc_resource_thumbnail_url(), ENT_COMPAT, "UTF-8"), 'title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8"))));
                     } else {
                         $feed->addItem(array('title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8"), 'description' => osc_item_description(), 'country' => osc_item_country(), 'region' => osc_item_region(), 'city' => osc_item_city(), 'city_area' => osc_item_city_area(), 'category' => osc_item_category(), 'dt_pub_date' => osc_item_pub_date()));
                     }
                 }
             }
             osc_run_hook('feed', $feed);
             $feed->dumpXML();
         } else {
             osc_run_hook('feed_' . $p_sFeed, $aItems);
         }
     }
 }
    $ipad = str_repeat(chr(0x36), $blocksize);
    $opad = str_repeat(chr(0x5c), $blocksize);
    $hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
    return bin2hex($hmac);
}
/*
 * Used to encode a field for Amazon Auth
 * (taken from the Amazon S3 PHP example library)
 */
function hex2b64($str)
{
    $raw = '';
    for ($i = 0; $i < strlen($str); $i += 2) {
        $raw .= chr(hexdec(substr($str, $i, 2)));
    }
    return base64_encode($raw);
}
if (count($argv) != 3) {
    echo "Usage: " . $argv[0] . " <S3 Policy File> <S3 secret key>\n";
    exit(1);
}
$policy = file_get_contents($argv[1]);
$secret = $argv[2];
/*
 * Base64 encode the Policy Document and then
 * create HMAC SHA-1 signature of the base64 encoded policy
 * using the secret key. Finally, encode it for Amazon Authentication.
 */
$base64_policy = base64_encode($policy);
$signature = hex2b64(hmacsha1($secret, $base64_policy));
echo "S3_POLICY=\"" . $base64_policy . "\"\nS3_SIGNATURE=\"" . $signature . "\"\n";
Example #8
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             foreach ($cities as $k => $city) {
                 $cities[$k]['label'] = $city['label'] . " (" . $city['region'] . ")";
             }
             echo json_encode($cities);
             break;
         case 'location_countries':
             // This is the autocomplete AJAX
             $countries = Country::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($countries);
             break;
         case 'location_regions':
             // This is the autocomplete AJAX
             $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country"));
             echo json_encode($regions);
             break;
         case 'location_cities':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region"));
             echo json_encode($cities);
             break;
         case 'delete_image':
             // Delete images via AJAX
             $ajax_photo = Params::getParam('ajax_photo');
             $id = Params::getParam('id');
             $item = Params::getParam('item');
             $code = Params::getParam('code');
             $secret = Params::getParam('secret');
             $json = array();
             if ($ajax_photo != '') {
                 $files = Session::newInstance()->_get('ajax_files');
                 $success = false;
                 foreach ($files as $uuid => $file) {
                     if ($file == $ajax_photo) {
                         $filename = $files[$uuid];
                         unset($files[$uuid]);
                         Session::newInstance()->_set('ajax_files', $files);
                         $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
                         break;
                     }
                 }
                 echo json_encode(array('success' => $success, 'msg' => $success ? _m('The selected photo has been successfully deleted') : _m("The selected photo couldn't be deleted")));
                 return false;
             }
             if (Session::newInstance()->_get('userId') != '') {
                 $userId = Session::newInstance()->_get('userId');
                 $user = User::newInstance()->findByPrimaryKey($userId);
             } else {
                 $userId = null;
                 $user = null;
             }
             // Check for required fields
             if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) {
                 $json['success'] = false;
                 $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             $aItem = Item::newInstance()->findByPrimaryKey($item);
             // Check if the item exists
             if (count($aItem) == 0) {
                 $json['success'] = false;
                 $json['msg'] = _m("The listing doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             if (!osc_is_admin_user_logged_in()) {
                 // Check if the item belong to the user
                 if ($userId != null && $userId != $aItem['fk_i_user_id']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
                 // Check if the secret passphrase match with the item
                 if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
             }
             // Does id & code combination exist?
             $result = ItemResource::newInstance()->existResource($id, $code);
             if ($result > 0) {
                 $resource = ItemResource::newInstance()->findByPrimaryKey($id);
                 if ($resource['fk_i_item_id'] == $item) {
                     // Delete: file, db table entry
                     if (defined(OC_ADMIN)) {
                         osc_deleteResource($id, true);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'admin', osc_logged_admin_id());
                     } else {
                         osc_deleteResource($id, false);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'user', osc_logged_user_id());
                     }
                     ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code));
                     $json['msg'] = _m('The selected photo has been successfully deleted');
                     $json['success'] = 'true';
                 } else {
                     $json['msg'] = _m("The selected photo does not belong to you");
                     $json['success'] = 'false';
                 }
             } else {
                 $json['msg'] = _m("The selected photo couldn't be deleted");
                 $json['success'] = 'false';
             }
             echo json_encode($json);
             return true;
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $encoded_alert = Params::getParam("alert");
             $alert = osc_decrypt_alert(base64_decode($encoded_alert));
             // check alert integrity / signature
             $stringToSign = osc_get_alert_public_key() . $encoded_alert;
             $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign));
             $server_signature = Session::newInstance()->_get('alert_signature');
             if ($server_signature != $signature) {
                 echo '-2';
                 return false;
             }
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if (osc_is_web_user_logged_in()) {
                 $userid = osc_logged_user_id();
                 $user = User::newInstance()->findByPrimaryKey($userid);
                 $email = $user['s_email'];
             }
             if ($alert != '' && $email != '') {
                 if (osc_validate_email($email)) {
                     $secret = osc_genRandomPassword();
                     if ($alertID = Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) {
                         if ((int) $userid > 0) {
                             $user = User::newInstance()->findByPrimaryKey($userid);
                             if ($user['b_active'] == 1 && $user['b_enabled'] == 1) {
                                 Alerts::newInstance()->activate($alertID);
                                 echo '1';
                                 return true;
                             } else {
                                 echo '-1';
                                 return false;
                             }
                         } else {
                             $aAlert = Alerts::newInstance()->findByPrimaryKey($alertID);
                             osc_run_hook('hook_email_alert_validation', $aAlert, $email, $secret);
                         }
                         echo "1";
                     } else {
                         echo "0";
                     }
                     return true;
                 } else {
                     echo '-1';
                     return false;
                 }
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             // run hooks
             $hook = Params::getParam('hook');
             if ($hook == '') {
                 echo json_encode(array('error' => 'hook parameter not defined'));
                 break;
             }
             switch ($hook) {
                 case 'item_form':
                     osc_run_hook('item_form', Params::getParam('catId'));
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     osc_run_hook('ajax_' . $hook);
                     break;
             }
             break;
         case 'custom':
             // Execute via AJAX custom file
             if (Params::existParam('route')) {
                 $routes = Rewrite::newInstance()->getRoutes();
                 $rid = Params::getParam('route');
                 $file = '../';
                 if (isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                     $file = $routes[$rid]['file'];
                 }
             } else {
                 // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                 // This will be REMOVED in 3.4
                 $file = Params::getParam('ajaxfile');
             }
             if ($file == '') {
                 echo json_encode(array('error' => 'no action defined'));
                 break;
             }
             // valid file?
             if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || stripos($file, '/admin/') !== false) {
                 //If the file is inside an "admin" folder, it should NOT be opened in frontend
                 echo json_encode(array('error' => 'no valid ajaxFile'));
                 break;
             }
             if (!file_exists(osc_plugins_path() . $file)) {
                 echo json_encode(array('error' => "ajaxFile doesn't exist"));
                 break;
             }
             require_once osc_plugins_path() . $file;
             break;
         case 'check_username_availability':
             $username = osc_sanitize_username(Params::getParam('s_username'));
             if (!osc_is_username_blacklisted($username)) {
                 $user = User::newInstance()->findByUsername($username);
                 if (isset($user['s_username'])) {
                     echo json_encode(array('exists' => 1, 's_username' => $username));
                 } else {
                     echo json_encode(array('exists' => 0, 's_username' => $username));
                 }
             } else {
                 echo json_encode(array('exists' => 1, 's_username' => $username));
             }
             break;
         case 'ajax_upload':
             // Include the uploader class
             require_once LIB_PATH . "AjaxUploader.php";
             $uploader = new AjaxUploader();
             $original = pathinfo($uploader->getOriginalName());
             $filename = uniqid("qqfile_") . "." . $original['extension'];
             $result = $uploader->handleUpload(osc_content_path() . 'uploads/temp/' . $filename);
             $result['uploadName'] = $filename;
             echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
             break;
         case 'ajax_validate':
             $id = Params::getParam('id');
             if (!is_numeric($id)) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $secret = Params::getParam('secret');
             $item = Item::newInstance()->findByPrimaryKey($id);
             if ($item['s_secret'] != $secret) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $nResources = ItemResource::newInstance()->countResources($id);
             $result = array('success' => $nResources < osc_max_images_per_item(), 'count' => $nResources);
             echo json_encode($result);
             break;
         case 'delete_ajax_upload':
             $files = Session::newInstance()->_get('ajax_files');
             $success = false;
             $filename = '';
             if (isset($files[Params::getParam('qquuid')]) && $files[Params::getParam('qquuid')] != '') {
                 $filename = $files[Params::getParam('qquuid')];
                 unset($files[Params::getParam('qquuid')]);
                 Session::newInstance()->_set('ajax_files', $files);
                 $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
             }
             echo json_encode(array('success' => $success, 'uploadName' => $filename));
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
function put_to_s3($temp_file_loc)
{
    //the date and time in rfc 822
    $rfc_822_datetime = date("r");
    //file key is an md5 hash of the file path and name
    $file_key = md5($temp_file_loc);
    //assemble your s3 signature
    $s3_signature = "PUT\n\nimage/gif\n" . $rfc_822_datetime . "\nx-amz-acl:" . ACL_SETTING . "\n/" . BUCKET_NAME . "/" . $file_key;
    $hasher =& new Crypt_HMAC(S3_SECRET_KEY, "sha1");
    $signature = hex2b64($hasher->hash($s3_signature));
    //make the request to create the file in the bucket
    $s3req =& new HTTP_Request(S3_URL . BUCKET_NAME . "/" . $file_key);
    $s3req->setMethod('PUT');
    $s3req->addHeader("content-type", 'image/gif');
    $s3req->addHeader("Date", $rfc_822_datetime);
    $s3req->addHeader("x-amz-acl", ACL_SETTING);
    $s3req->addHeader("Authorization", "AWS " . S3_ACCESS_KEY . ":" . $signature);
    $s3req->setBody(file_get_contents($temp_file_loc));
    $s3req->sendRequest();
    if ($s3req->getResponseCode() != 200) {
        echo $s3req->getResponseBody();
        die("Problem creating file for " . $temp_file_loc . " (" . $file_key . ") - Status was " . $s3req->getResponseCode() . "\n");
    } else {
        return S3_URL . BUCKET_NAME . "/" . $file_key;
    }
}
Example #10
0
    public function getUploadFields()
    {
        $redirect = "http://" . SITE_HOSTNAME . "/upload/success";
        $acl = "public-read";
        $expiration = gmdate("Y-m-d\\TH:i:s\\Z", strtotime("+1 day"));
        //create amazons crazy policy data array.
        $policy_json = '
			{
				"expiration": "' . $expiration . '",
				"conditions": [
					{"acl": "' . $acl . '"},
					{"bucket": "' . AMAZON_S3_BUCKET_NAME . '"},
					["starts-with", "$key", "uploads/"],
					["starts-with", "$Content-Type", ""],
					["starts-with", "$Content-Disposition", ""],
					{"success_action_redirect": "' . $redirect . '"},
					["content-length-range", 1, 262144000]
				]
			}';
        //create our various encoded/signed stuff.
        $policy_json_cleaned = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $policy_json);
        $policy_encoded = base64_encode($policy_json_cleaned);
        $signature = hex2b64(hash_hmac('sha1', $policy_encoded, AMAZON_AWS_SECRET));
        $fields = array();
        $fields["AWSAccessKeyId"] = AMAZON_AWS_KEY;
        $fields["key"] = "uploads/\${filename}";
        $fields["acl"] = $acl;
        $fields["success_action_redirect"] = $redirect;
        $fields["policy"] = $policy_encoded;
        $fields["signature"] = $signature;
        $fields["Content-Type"] = "";
        $fields["Content-Disposition"] = "";
        return $fields;
    }
function modhex2b64($modhex_str)
{
    $hex_str = strtr($modhex_str, "cbdefghijklnrtuv", "0123456789abcdef");
    return hex2b64($hex_str);
}
Example #12
0
     $s3keystart = $GLOBALS['settings']['s3']['paths']['job-input']['@attributes']['value'];
     $s3acl = $GLOBALS['settings']['s3']['upload']['default-acl']['@attributes']['value'];
     $aws_secret_access_key = $GLOBALS['settings']['s3']['secret-key']['@attributes']['value'];
     $aws_access_key = $GLOBALS['settings']['s3']['access-key']['@attributes']['value'];
     $s3timestamp = $GLOBALS['settings']['s3']['file-expiration']['@attributes']['value'];
     $s3filename = $s3keystart . "/" . sha1(time() . $qn) . ".\${filename}";
     //what extension to use?
     //$s3redirect=str_replace("{uri}",$this_server_url,$s3redirect);
     //$s3redirect=str_replace("{qid}",$qn,$s3redirect);
     $policy_doc = "{'expiration': '{$s3timestamp}','conditions': [ {'bucket': '{$s3bucket}'},['starts-with', '\$key', '{$s3keystart}'],{'acl': '{$s3acl}'},{'success_action_redirect': '{$s3redirect}'},['starts-with', '\$Content-Type', ''],['content-length-range', 0, 104857600000]]}";
     $policy_doc_encoded = base64_encode($policy_doc);
     //echo $policy_doc."<br/>";
     //$signature = urlencode(base64_encode(hash_hmac("sha1",utf8_encode($policy_doc_encoded),$aws_secret_access_key,true)));
     //$signature = (base64_encode(hash_hmac("sha1",($policy_doc_encoded),$aws_secret_access_key)));
     //$signature = base64_encode(hash_hmac('sha256', $policy_doc, $aws_secret_access_key, true));
     $signature = hex2b64(hmacsha1($aws_secret_access_key, $policy_doc_encoded));
     //echo $signature."<br/>";
     echo "<form style='display:inline;' action='https://{$s3bucket}.s3.amazonaws.com/' method='post' enctype='multipart/form-data'>";
     echo "<input type='hidden' name='key' value='{$s3filename}'>";
     echo "<input type='hidden' name='AWSAccessKeyId' value='{$aws_access_key}'>";
     echo "<input type='hidden' name='acl' value='{$s3acl}'>";
     echo "<input type='hidden' name='success_action_redirect' value='{$s3redirect}'>";
     echo "<input type='hidden' name='policy' value='{$policy_doc_encoded}'>";
     echo "<input type='hidden' name='signature' value='{$signature}'>";
     echo "<input type='hidden' name='Content-Type' value='application/octet-stream'>";
     echo "<input name='file' value='Browse...' type='file' style='background-color:" . rcolor() . ";display:inline;'><input type='submit' value='";
     echo getTranslation("Start File Upload", $settings);
     echo "' style='background-color:" . rcolor() . ";display:inline;'>";
     echo "</form>";
 } else {
     echo getTranslation("Not available in demo", $settings);