/** * Migrate data according to a scenario * @param $scenario */ private function _migrate_data($scenario) { $this->EE = get_instance(); $db = $this->EE->db; $this->EE->load->library('assets_lib'); clearstatcache(); switch ($scenario) { case '<2 -> 2.0': require_once PATH_THIRD . 'assets/sources/ee/source.ee.php'; $filedirs = array(); $folder_list = array(); // load upload preferences and store them in table for Assets $rows = $db->get('upload_prefs')->result(); foreach ($rows as $filedir) { $filedirs[$filedir->id] = Assets_ee_source::apply_filedir_overrides($filedir); } // load physical folder structure foreach ($filedirs as $id => $filedir) { $filedir->server_path = Assets_ee_source::resolve_server_path($filedir->server_path); $folder_list[$id][] = $filedir->server_path; $this->_load_folder_structure($filedir->server_path, $folder_list[$id]); } // store the folder structure in database $subfolders = array(); foreach ($folder_list as $filedir_id => $folders) { $filedir = $filedirs[$filedir_id]; foreach ($folders as $folder) { $subpath = substr($folder, strlen($filedir->server_path)); if (empty($subpath)) { $folder_name = $filedir->name; $parent_id = NULL; } else { $path_parts = explode('/', $subpath); $folder_name = array_pop($path_parts); $parent_key = $filedir_id . ':' . rtrim(join('/', $path_parts), '/'); $parent_id = isset($subfolders[$parent_key]) ? $subfolders[$parent_key] : 0; } // in case false was returned earlier $subpath = $subpath ? rtrim($subpath, '/') . '/' : ''; $folder_entry = array('source_type' => 'ee', 'filedir_id' => $filedir_id, 'folder_name' => $folder_name, 'full_path' => $subpath); if (!is_null($parent_id)) { $folder_entry['parent_id'] = $parent_id; } $this->EE->db->insert('assets_folders', $folder_entry); $subfolders[$filedir_id . ':' . rtrim($subpath, '/')] = $this->EE->db->insert_id(); } } // bring up the list of existing assets and update the entries $rows = $db->get('assets_files')->result(); $pattern = '/\\{filedir_(?P<filedir_id>[0-9]+)\\}(?P<path>.*)/'; foreach ($rows as $asset) { $asset->connector = 'ee'; if (preg_match($pattern, $asset->file_name, $matches)) { if (isset($filedirs[$matches['filedir_id']])) { $filedir = $filedirs[$matches['filedir_id']]; $full_path = str_replace('{filedir_' . $filedir->id . '}', $filedir->server_path, $asset->file_name); $subpath = substr($full_path, strlen($filedir->server_path)); $path_parts = explode('/', $subpath); $file = array_pop($path_parts); $subpath = join('/', $path_parts); $folder_key = $matches['filedir_id'] . ':' . $subpath; if (isset($subfolders[$folder_key])) { $folder_id = $subfolders[$folder_key]; } else { $folder_id = 0; } $kind = Assets_helper::get_kind($full_path); $data = array('source_type' => 'ee', 'filedir_id' => $filedir->id, 'folder_id' => $folder_id, 'file_name' => $file, 'kind' => $kind); if (file_exists($full_path)) { $data['size'] = filesize($full_path); $data['date_modified'] = filemtime($full_path); if ($kind == 'image') { list($width, $height) = getimagesize($full_path); $data['width'] = $width; $data['height'] = $height; } } $this->EE->db->update('assets_files', $data, array('file_id' => $asset->file_id)); $this->EE->assets_lib->update_file_search_keywords($asset->file_id); } } } // celebrate break; case '2.0b1 -> 2.0b2': // get S3 credentials if any $query = $this->EE->db->select('settings')->where('name', 'assets')->get('fieldtypes'); $settings = unserialize(base64_decode($query->row('settings'))); $settings = array_merge(array('license_key' => '', 's3_access_key_id' => '', 's3_secret_access_key' => ''), $settings); //if we have s3 settings, let's convert the "folder_prefs" way to "sources" way if (!empty($settings['s3_access_key_id']) && !empty($settings['s3_secret_access_key'])) { $old_sources = $this->EE->db->get('assets_sources')->result(); foreach ($old_sources as $source) { $previous_settings = json_decode($source->settings); $new_settings = (object) array('access_key_id' => $settings['s3_access_key_id'], 'secret_access_key' => $settings['s3_secret_access_key'], 'bucket' => $previous_settings->name, 'url_prefix' => $previous_settings->url_prefix, 'location' => $previous_settings->location); $data = array('name' => $previous_settings->name, 'settings' => Assets_helper::get_json($new_settings)); $this->EE->db->update('assets_sources', $data, array('source_id' => $source->source_id)); } } // modify folder data and also keep a list of who's who $folders = $this->EE->db->get('assets_folders')->result(); $folder_sources = array(); foreach ($folders as $row) { if ($row->source_type == 'ee') { $row->filedir_id = $row->source_id; $row->source_id = NULL; $this->EE->db->update('assets_folders', $row, array('folder_id' => $row->folder_id)); $folder_sources[$row->folder_id] = $row->filedir_id; } else { $folder_sources[$row->folder_id] = $row->source_id; } } // add some data for file entries and we're done! $files = $this->EE->db->get('assets_files')->result(); foreach ($files as $row) { if ($row->source_type == 'ee' && isset($folder_sources[$row->folder_id])) { $row->source_id = NULL; $row->filedir_id = $folder_sources[$row->folder_id]; $this->EE->db->update('assets_files', $row, array('file_id' => $row->file_id)); } else { if (isset($folder_sources[$row->folder_id])) { $row->source_id = $folder_sources[$row->folder_id]; $row->filedir_id = NULL; $this->EE->db->update('assets_files', $row, array('file_id' => $row->file_id)); } } } // party! break; } }
/** * Get Language JS */ public static function get_lang_js() { $json = array(); foreach (func_get_args() as $line) { $json[$line] = lang($line); } return 'Assets.lang = ' . Assets_helper::get_json($json) . ';'; }
/** * Build Field */ private function _build_field($data, $context) { // include the resources Assets_helper::include_sheet_resources(); // prep the settings $this->_prep_settings($this->settings); // ------------------------------------------- // Field HTML // ------------------------------------------- if ($is_cell = isset($this->cell_name)) { $vars['field_name'] = $this->cell_name; $vars['field_id'] = str_replace(array('[', ']'), array('_', ''), $this->cell_name); } else { if ($this->var_id) { $vars['field_name'] = $this->field_name; $vars['field_id'] = str_replace(array('[', ']'), array('_', ''), $this->field_name); } else { if ($this->element_id) { $vars['field_name'] = $this->field_name; $vars['field_id'] = $this->_extract_element_id($this->field_name); } else { if ($context == 'grid') { $cell_name = 'col_id_' . $this->settings['col_id']; $vars['field_id'] = $vars['field_name'] = $cell_name; } else { $vars['field_name'] = $vars['field_id'] = $this->field_name; } } } } // ------------------------------------------- // Get the selected files // ------------------------------------------- $entry_id = $this->EE->input->get('entry_id'); $vars['files'] = array(); // if there was a validation error, EE's already passed us the post array if (is_array($data)) { foreach ($data as $file_id) { if (!empty($file_id)) { $file = $this->EE->assets_lib->get_file_by_id($file_id, TRUE); if ($file !== FALSE) { $vars['files'][] = $file; } } } } else { if ($context == 'channel' && $this->EE->input->get('entry_id') || $context == 'matrix' && isset($this->row_id) || $context == 'grid' && isset($this->settings['grid_row_id']) && isset($this->settings['col_id']) || $context == 'low' || $context == 'content_elements') { if ($context == 'grid') { // Set up these properties so we can select data the same way we do for Matrix $this->row_id = $this->settings['grid_row_id']; $this->col_id = $this->settings['col_id']; // Also stop lying about our field id. $this->field_id = $this->settings['grid_field_id']; } $sql = "SELECT DISTINCT a.source_type, a.folder_id, a.file_name, a.file_id, af.source_id, af.filedir_id\n\t\t\t FROM exp_assets_files AS a\n\t\t\t INNER JOIN exp_assets_selections AS ae ON ae.file_id = a.file_id\n\t\t\t INNER JOIN exp_assets_folders AS af ON af.folder_id = a.folder_id\n\t\t\t WHERE"; switch ($context) { case 'low': $sql .= " ae.var_id = {$this->var_id}"; break; case 'content_elements': $element_id = $this->_extract_element_id($this->field_name); $sql .= ' ae.element_id = "' . $element_id . '"'; $is_draft = isset($this->EE->session->cache['ep_better_workflow']['is_draft']) && $this->EE->session->cache['ep_better_workflow']['is_draft']; $sql .= ' AND is_draft = ' . ($is_draft ? '1' : '0') . ' '; break; case 'matrix': case 'grid': $sql .= " ae.col_id = '{$this->col_id}'\n\t\t\t\t\t\t\t\t AND ae.row_id = '{$this->row_id}'\n\t\t\t\t\t\t\t\t AND"; if (!empty($this->var_id)) { $sql .= " ae.var_id = " . $this->var_id; } else { $entry_id = $this->EE->security->xss_clean($this->EE->input->get('entry_id')); if (!$entry_id) { $entry_id = $this->settings['entry_id']; } $sql .= " ae.entry_id " . ($entry_id ? "= '{$entry_id}'" : 'IS NULL') . " AND ae.field_id " . ($this->field_id ? "= '{$this->field_id}'" : 'IS NULL'); } break; case 'channel': $entry_id = $this->EE->security->xss_clean($this->EE->input->get('entry_id')); $sql .= " ae.entry_id " . ($entry_id ? "= '{$entry_id}'" : 'IS NULL') . " AND ae.field_id " . ($this->field_id ? "= '{$this->field_id}'" : 'IS NULL'); } $sql .= ' ORDER BY ae.sort_order'; if ($this->settings['multi'] == 'n') { $sql .= ' LIMIT 1'; } // ------------------------------------------- // 'assets_field_selections_query' hook // - Modify the row data before it gets saved to exp_assets_selections // if ($this->EE->extensions->active_hook('assets_field_selections_query')) { $query = $this->EE->extensions->call('assets_field_selections_query', $this, $sql); } else { $query = $this->EE->db->query($sql); } // // ------------------------------------------- foreach ($query->result() as $row) { try { if ($file = $this->EE->assets_lib->get_file_by_id($row->file_id, TRUE)) { $vars['files'][] = $file; } } catch (Exception $exception) { // these files are gone. } } } } $vars['multi'] = $this->settings['multi'] == 'y'; $vars['helper'] = $this->EE->assets_lib; if ($this->settings['view'] == 'thumbs') { // load the filemanager library and file helper for generating thumbs $this->EE->load->library('filemanager'); $this->EE->load->helper('file'); $vars['file_view'] = 'thumbview/thumbview'; $vars['thumb_size'] = $this->settings['thumb_size']; $vars['show_filenames'] = $this->settings['show_filenames'] == 'y'; } else { $vars['file_view'] = 'listview/listview'; $vars['cols'] = $this->settings['show_cols']; } if ($context == 'content_elements') { $vars['ce_options'] = Assets_helper::get_json($this->settings); } else { $vars['ce_options'] = NULL; } $r = $this->EE->load->view('field/field', $vars, TRUE); // Add a hidden input in case no files are selected $r .= '<input type="hidden" name="' . ($is_cell ? $this->cell_name : $this->field_name) . '[]" value="" />'; // Include any thumb CSS queued up by the field Assets_helper::insert_queued_css(); // ------------------------------------------- // Pass field settings to JS // ------------------------------------------- if (!$is_cell || !isset($this->cache['initialized_col_settings'][$this->col_id])) { if ($is_cell) { $namespace = 'col_id_' . $this->col_id; } else { if ($context == 'content_elements') { $namespace = 'element_id_' . $this->element_id; } else { $namespace = 'field_id_' . $this->field_id; } } $settings_json = Assets_helper::get_json(array('filedirs' => $this->settings['filedirs'], 'multi' => $vars['multi'], 'view' => $this->settings['view'], 'thumb_size' => $this->settings['thumb_size'], 'show_filenames' => $this->settings['show_filenames'], 'show_cols' => $this->settings['show_cols'], 'namespace' => $namespace)); if ($is_cell) { Assets_helper::insert_js('Assets.Field.matrixConfs.col_id_' . $this->col_id . ' = ' . $settings_json . ';'); $this->cache['initialized_col_settings'][$this->col_id] = TRUE; } if (!empty($this->element_id)) { if ($this->field_name != '__element_name__[__index__][data]') { $field_id = $this->_extract_element_id($this->field_name); Assets_helper::insert_js("new Assets.Field('{$field_id}', '{$this->field_name}', {$settings_json});"); } } else { if ($context == 'grid') { Assets_helper::insert_js('Assets.Field.gridConfs.col_id_' . $this->settings['col_id'] . ' = ' . $settings_json . ';'); } else { $field_id = preg_replace('/[^\\w\\-]+/', '_', $vars['field_id']); Assets_helper::insert_js("new Assets.Field('{$field_id}', '{$this->field_name}', {$settings_json});"); } } } return $r; }
/** * Refresh a connection information and return authorization token. * * @throws Exception */ private function _refresh_connection_information() { $settings = $this->_source_settings; $username = $settings->username; $api_key = $settings->api_key; $headers = array('Content-Type: application/json', 'Accept: application/json'); $payload = Assets_helper::get_json(array('auth' => array('RAX-KSKEY:apiKeyCredentials' => array('username' => $username, 'apiKey' => $api_key)))); $target_url = self::_make_authorization_request_url(); $response = self::_do_request($target_url, 'POST', $headers, array(), $payload); $body = json_decode(substr($response, strpos($response, '{'))); if (!$body) { throw new Exception(lang('wrong_credentials')); } $token = $body->access->token->id; $services = $body->access->serviceCatalog; if (!$token || !$services) { throw new Exception(lang('wrong_credentials')); } $regions = array(); // Fetch region information foreach ($services as $service) { if ($service->name == 'cloudFilesCDN' || $service->name == 'cloudFiles') { foreach ($service->endpoints as $endpoint) { if (empty($regions[$endpoint->region])) { $regions[$endpoint->region] = array(); } if ($service->name == 'cloudFilesCDN') { $regions[$endpoint->region]['cdn_url'] = $endpoint->publicURL; } else { $regions[$endpoint->region]['storage_url'] = $endpoint->publicURL; } } } } // Each region gets separate connection information foreach ($regions as $region => $data) { $connection_key = $this->_get_connection_key($username, $api_key, $region); $data = array('token' => $token, 'storage_url' => $data['storage_url'], 'cdn_url' => $data['cdn_url']); // Store this in the access store self::$_access_store[$connection_key] = $data; $this->_update_access_data($connection_key, $data); } }
/** * Get upload POST parameters for form uploads * * @param string $bucket Bucket name * @param string $uriPrefix Object URI prefix * @param constant $acl ACL constant * @param integer $lifetime Lifetime in seconds * @param integer $maxFileSize Maximum filesize in bytes (default 5MB) * @param string $successRedirect Redirect URL or 200 / 201 status code * @param array $amzHeaders Array of x-amz-meta-* headers * @param array $headers Array of request headers or content type as a string * @param boolean $flashVars Includes additional "Filename" variable posted by Flash * @return object */ public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600, $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false) { // Create policy object $policy = new stdClass(); $policy->expiration = gmdate('Y-m-d\\TH:i:s\\Z', time() + $lifetime); $policy->conditions = array(); $obj = new stdClass(); $obj->bucket = $bucket; array_push($policy->conditions, $obj); $obj = new stdClass(); $obj->acl = $acl; array_push($policy->conditions, $obj); $obj = new stdClass(); // 200 for non-redirect uploads if (is_numeric($successRedirect) && in_array((int) $successRedirect, array(200, 201))) { $obj->success_action_status = (string) $successRedirect; } else { // URL $obj->success_action_redirect = $successRedirect; } array_push($policy->conditions, $obj); if ($acl !== self::ACL_PUBLIC_READ) { array_push($policy->conditions, array('eq', '$acl', $acl)); } array_push($policy->conditions, array('starts-with', '$key', $uriPrefix)); if ($flashVars) { array_push($policy->conditions, array('starts-with', '$Filename', '')); } foreach (array_keys($headers) as $headerKey) { array_push($policy->conditions, array('starts-with', '$' . $headerKey, '')); } foreach ($amzHeaders as $headerKey => $headerVal) { $obj = new stdClass(); $obj->{$headerKey} = (string) $headerVal; array_push($policy->conditions, $obj); } array_push($policy->conditions, array('content-length-range', 0, $maxFileSize)); $policy = base64_encode(str_replace('\\/', '/', Assets_helper::get_json($policy))); // Create parameters $params = new stdClass(); $params->AWSAccessKeyId = self::$__accessKey; $params->key = $uriPrefix . '${filename}'; $params->acl = $acl; $params->policy = $policy; unset($policy); $params->signature = self::__getHash($params->policy); if (is_numeric($successRedirect) && in_array((int) $successRedirect, array(200, 201))) { $params->success_action_status = (string) $successRedirect; } else { $params->success_action_redirect = $successRedirect; } foreach ($headers as $headerKey => $headerVal) { $params->{$headerKey} = (string) $headerVal; } foreach ($amzHeaders as $headerKey => $headerVal) { $params->{$headerKey} = (string) $headerVal; } return $params; }
/** * Save source */ public function save_source() { if ($this->EE->session->userdata['group_id'] != 1) { $this->_forbidden(); } $name = $this->EE->input->post('source_name'); if (!empty($name)) { $name = htmlentities($name); $save_data = array(); $field_list = $this->EE->assets_lib->get_source_settings_field_list(); $source_type = $this->EE->input->post('source_type'); foreach ($field_list[$source_type] as $field) { $save_data[$field] = $this->EE->input->post($source_type . '_' . $field); } switch ($source_type) { case 's3': $save_data['bucket'] = $this->EE->input->post('s3_bucket'); $save_data['url_prefix'] = $this->EE->input->post('s3_bucket_url_prefix'); $save_data['location'] = $this->EE->input->post('s3_bucket_location'); $save_data['cf_distribution'] = $this->EE->input->post('cf_distribution'); $save_data['cache_amount'] = (int) $this->EE->input->post('s3_cache_amount'); $period = $this->EE->input->post('s3_cache_period'); $save_data['cache_period'] = preg_match('/seconds|minutes|hours|days/', $period) ? $period : ''; break; case 'gc': $save_data['bucket'] = $this->EE->input->post('gc_bucket'); $save_data['url_prefix'] = $this->EE->input->post('gc_bucket_url_prefix'); $save_data['cache_amount'] = (int) $this->EE->input->post('gc_cache_amount'); $period = $this->EE->input->post('gc_cache_period'); $save_data['cache_period'] = preg_match('/seconds|minutes|hours|days/', $period) ? $period : ''; break; case 'rs': $save_data['region'] = $this->EE->input->post('rs_region'); $save_data['container'] = $this->EE->input->post('rs_container'); $save_data['url_prefix'] = $this->EE->input->post('rs_container_url_prefix'); } $source_id = $this->EE->input->post('source_id'); $data = array('name' => $name, 'settings' => Assets_helper::get_json($save_data)); $this->EE->assets_lib->store_source($source_type, $source_id, $data); // change the name for the top level folder as well $this->EE->assets_lib->rename_source_folder($source_id, $source_type, $name); $this->EE->session->set_flashdata('message_success', lang('source_saved')); } $this->EE->functions->redirect(BASE . AMP . $this->base . AMP . 'method=sources'); }