/**
 * Submit Mobile Blocks settings.
 * @param $values
 * @param $theme
 * @param $generated_files_path
 */
function at_core_submit_mobile_blocks($values, $theme, $generated_files_path)
{
    $mobile_blocks_css = array();
    // TODO entityManager() is deprecated, but how to replace?
    $theme_blocks = \Drupal::entityManager()->getStorage('block')->loadByProperties(['theme' => $theme]);
    if (!empty($theme_blocks)) {
        foreach ($theme_blocks as $block_key => $block_values) {
            $block_id = $block_values->id();
            if (isset($values['settings_mobile_block_show_' . $block_id]) && $values['settings_mobile_block_show_' . $block_id] == 1) {
                $block_selector = '#' . Html::getUniqueId('block-' . $block_id);
                $mobile_blocks_css[] = $block_selector . ' {display:none}' . "\n";
                $mobile_blocks_css[] = '.is-mobile ' . $block_selector . ' {display:block}' . "\n";
            }
            if (isset($values['settings_mobile_block_hide_' . $block_id]) && $values['settings_mobile_block_hide_' . $block_id] == 1) {
                $block_selector = '#' . Html::getUniqueId('block-' . $block_id);
                $mobile_blocks_css[] = '.is-mobile ' . $block_selector . ' {display:none}' . "\n";
                $mobile_blocks_css[] = $block_selector . ' {display:block}' . "\n";
            }
        }
    }
    if (!empty($mobile_blocks_css)) {
        $file_name = 'mobile-blocks.css';
        $filepath = $generated_files_path . '/' . $file_name;
        file_unmanaged_save_data($mobile_blocks_css, $filepath, FILE_EXISTS_REPLACE);
    }
}
Exemple #2
0
 /**
  * {@inheritdoc}
  *
  * The file name for the CSS or JS cache file is generated from the hash of
  * the aggregated contents of the files in $data. This forces proxies and
  * browsers to download new CSS when the CSS changes.
  */
 public function dump($data, $file_extension)
 {
     // Prefix filename to prevent blocking by firewalls which reject files
     // starting with "ad*".
     $filename = $file_extension . '_' . Crypt::hashBase64($data) . '.' . $file_extension;
     // Create the css/ or js/ path within the files folder.
     $path = 'public://' . $file_extension;
     $uri = $path . '/' . $filename;
     // Create the CSS or JS file.
     file_prepare_directory($path, FILE_CREATE_DIRECTORY);
     if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
         return FALSE;
     }
     // If CSS/JS gzip compression is enabled and the zlib extension is available
     // then create a gzipped version of this file. This file is served
     // conditionally to browsers that accept gzip using .htaccess rules.
     // It's possible that the rewrite rules in .htaccess aren't working on this
     // server, but there's no harm (other than the time spent generating the
     // file) in generating the file anyway. Sites on servers where rewrite rules
     // aren't working can set css.gzip to FALSE in order to skip
     // generating a file that won't be used.
     if (extension_loaded('zlib') && \Drupal::config('system.performance')->get($file_extension . '.gzip')) {
         if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
             return FALSE;
         }
     }
     return $uri;
 }
Exemple #3
0
 function complie($file = null)
 {
     $update = drupalexp_is_settings_change();
     $ftime = $this->filetime($file);
     if (!empty($this->theme->lessc)) {
         foreach ($this->theme->lessc as $lessc_file) {
             if ($ftime < $this->filetime($lessc_file)) {
                 $update = true;
             }
             $this->output .= "@import \"{$lessc_file}\";\n";
         }
     }
     if ($update) {
         try {
             $this->css = $this->lessc->compile($this->output);
         } catch (exception $e) {
             drupal_set_message("fatal error: " . $e->getMessage(), 'error');
             return FALSE;
         }
         if ($file) {
             file_unmanaged_save_data($this->css, $file, FILE_EXISTS_REPLACE);
         }
     }
     return $this->css;
 }
 /**
  * Tests export of configuration.
  */
 function testExport()
 {
     // Verify the export page with export submit button is available.
     $this->drupalGet('admin/config/development/configuration/full/export');
     $this->assertFieldById('edit-submit', t('Export'));
     // Submit the export form and verify response.
     $this->drupalPostForm('admin/config/development/configuration/full/export', array(), t('Export'));
     $this->assertResponse(200, 'User can access the download callback.');
     // Get the archived binary file provided to user for download.
     $archive_data = $this->drupalGetContent();
     // Temporarily save the archive file.
     $uri = file_unmanaged_save_data($archive_data, 'temporary://config.tar.gz');
     // Extract the archive and verify it's not empty.
     $file_path = file_directory_temp() . '/' . file_uri_target($uri);
     $archiver = new Tar($file_path);
     $archive_contents = $archiver->listContents();
     $this->assert(!empty($archive_contents), 'Downloaded archive file is not empty.');
     // Prepare the list of config files from active storage, see
     // \Drupal\config\Controller\ConfigController::downloadExport().
     $storage_active = $this->container->get('config.storage');
     $config_files = array();
     foreach ($storage_active->listAll() as $config_name) {
         $config_files[] = $config_name . '.yml';
     }
     // Assert that the downloaded archive file contents are the same as the test
     // site active store.
     $this->assertIdentical($archive_contents, $config_files);
     // Ensure the test configuration override is in effect but was not exported.
     $this->assertIdentical(\Drupal::config('system.maintenance')->get('message'), 'Foo');
     $archiver->extract(file_directory_temp(), array('system.maintenance.yml'));
     $file_contents = file_get_contents(file_directory_temp() . '/' . 'system.maintenance.yml');
     $exported = Yaml::decode($file_contents);
     $this->assertNotIdentical($exported['message'], 'Foo');
 }
 /**
  * {@inheritdoc}
  */
 public function denormalize($data, $class, $format = NULL, array $context = array())
 {
     $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody();
     $path = 'temporary://' . drupal_basename($data['uri'][0]['value']);
     $data['uri'] = file_unmanaged_save_data($file_data, $path);
     return $this->entityManager->getStorage('file')->create($data);
 }
/**
 * @file
 * Save Breadcrumb CSS to file
 */
function at_core_submit_mobile_blocks($values, $theme, $generated_files_path) {
  $mobile_blocks_css = array();
  $theme_blocks = entity_load_multiple_by_properties('block', ['theme' => $theme]);

  if (!empty($theme_blocks)) {
    foreach ($theme_blocks as $block_key => $block_values) {
      $block_id = $block_values->id();
      if (isset($values['settings_mobile_block_show_' . $block_id]) && $values['settings_mobile_block_show_' . $block_id] == 1) {
        $block_selector = '#' . Html::getUniqueId('block-' . $block_id);
        $mobile_blocks_css[] = $block_selector . ' {display:none}' . "\n";
        $mobile_blocks_css[] = '.is-mobile ' . $block_selector . ' {display:block}' . "\n";
      }
      if (isset($values['settings_mobile_block_hide_' . $block_id]) && $values['settings_mobile_block_hide_' . $block_id] == 1) {
        $block_selector = '#' . Html::getUniqueId('block-' . $block_id);
        $mobile_blocks_css[] = '.is-mobile ' . $block_selector . ' {display:none}' . "\n";
        $mobile_blocks_css[] = $block_selector . ' {display:block}' . "\n";
      }
    }
  }

  if (!empty($mobile_blocks_css)) {
    $file_name = 'mobile-blocks.css';
    $filepath = $generated_files_path . '/' . $file_name;
    file_unmanaged_save_data($mobile_blocks_css, $filepath, FILE_EXISTS_REPLACE);
  }
}
Exemple #7
0
 public function outputFile($file, $force = FALSE)
 {
     if (file_exists($file) && !$force) {
         $update = FALSE;
         $last_modified = filemtime($file);
         if (!empty($this->theme->lessc)) {
             foreach ($this->theme->lessc as $lessc) {
                 $path = $this->theme_path . '/lessc/' . $lessc;
                 if (filemtime($path) > $last_modified) {
                     $update = TRUE;
                     break;
                 }
             }
         }
     } else {
         $update = TRUE;
     }
     if ($update) {
         if ($this->css == '') {
             $this->compileLessc();
         }
         $file_update = file_unmanaged_save_data($this->css, $file, FILE_EXISTS_REPLACE);
         if (!$file_update) {
             return FALSE;
         }
     }
     return $file;
 }
Exemple #8
0
 function complie($file = null)
 {
     $update = drupalexp_is_settings_change();
     $ftime = $this->filetime($file);
     if (!empty($this->theme->lessc)) {
         foreach ($this->theme->lessc as $lessc_file) {
             if ($ftime < $this->filetime($lessc_file)) {
                 $update = true;
             }
             $this->output .= "@import \"{$lessc_file}\";\n";
         }
     }
     if ($update) {
         try {
             $this->css = $this->lessc->compile($this->output);
         } catch (exception $e) {
             drupal_set_message("fatal error: " . $e->getMessage(), 'error');
             return FALSE;
         }
         if ($file) {
             $css_output = "/*This file is generated by less css (http://lesscss.org) using drupalexp framework (http://drupalexp.com)*/\n/*Please do not modify this file content*/\n" . $this->css;
             file_unmanaged_save_data($css_output, $file, FILE_EXISTS_REPLACE);
         }
     }
     return $this->css;
 }
 /**
  * Tests if the module cleans up the disk on uninstall.
  */
 public function testPiwikUninstall()
 {
     $cache_path = 'public://piwik';
     $site_id = '1';
     $this->config('piwik.settings')->set('site_id', $site_id)->save();
     $this->config('piwik.settings')->set('url_http', 'http://www.example.com/piwik/')->save();
     $this->config('piwik.settings')->set('url_https', 'https://www.example.com/piwik/')->save();
     // Enable local caching of piwik.js
     $this->config('piwik.settings')->set('cache', 1)->save();
     // Load front page to get the piwik.js downloaded into local cache. But
     // loading the piwik.js is not possible as "url_http" is a test dummy only.
     // Create a dummy file to complete the rest of the tests.
     file_prepare_directory($cache_path, FILE_CREATE_DIRECTORY);
     file_unmanaged_save_data($this->randomMachineName(16), $cache_path . '/piwik.js');
     // Test if the directory and piwik.js exists.
     $this->assertTrue(file_prepare_directory($cache_path), 'Cache directory "public://piwik" has been found.');
     $this->assertTrue(file_exists($cache_path . '/piwik.js'), 'Cached piwik.js tracking file has been found.');
     // Uninstall the module.
     $edit = [];
     $edit['uninstall[piwik]'] = TRUE;
     $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
     $this->assertNoText(\Drupal::translation()->translate('Configuration deletions'), 'No configuration deletions listed on the module install confirmation page.');
     $this->drupalPostForm(NULL, NULL, t('Uninstall'));
     $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
     // Test if the directory and all files have been removed.
     $this->assertFalse(file_scan_directory($cache_path, '/.*/'), 'Cached JavaScript files have been removed.');
     $this->assertFalse(file_prepare_directory($cache_path), 'Cache directory "public://piwik" has been removed.');
 }
function at_core_submit_custom_css($values, $generated_files_path)
{
    $custom_css = '';
    if (!empty($values['settings_custom_css'])) {
        // sanitize user entered data
        $custom_css = Xss::filter($values['settings_custom_css']);
    }
    $file_name = 'custom-css.css';
    $filepath = $generated_files_path . '/' . $file_name;
    file_unmanaged_save_data($custom_css, $filepath, FILE_EXISTS_REPLACE);
}
Exemple #11
0
/**
 * @file
 * Save Breadcrumb CSS to file
 */
function at_core_submit_breadcrumb($values, $theme, $generated_files_path) {
  $breadcrumb_css = '';
  if (!empty($values['settings_breadcrumb_separator'])) {
    $css = '.breadcrumb li:before {content: "' . Html::escape($values['settings_breadcrumb_separator']) . '"}';
  }
  if (!empty($css)) {
    $file_name = 'breadcrumb.css';
    $filepath = $generated_files_path . '/' . $file_name;
    file_unmanaged_save_data($css, $filepath, FILE_EXISTS_REPLACE);
  }
}
 /**
  * Tests the deletion of stale files.
  */
 function testUpdateDeleteFileIfStale()
 {
     $file_name = file_unmanaged_save_data($this->randomMachineName());
     $this->assertNotNull($file_name);
     // During testing the file change and the stale checking occurs in the same
     // request, so the beginning of request will be before the file changes and
     // REQUEST_TIME - $filectime is negative. Set the maximum age to a number
     // even smaller than that.
     $this->container->get('config.factory')->get('system.file')->set('temporary_maximum_age', -100000)->save();
     $file_path = drupal_realpath($file_name);
     update_delete_file_if_stale($file_path);
     $this->assertFalse(is_file($file_path));
 }
 /**
  * Tests export of configuration.
  */
 function testExport()
 {
     // Verify the export page with export submit button is available.
     $this->drupalGet('admin/config/development/configuration/full/export');
     $this->assertFieldById('edit-submit', t('Export'));
     // Submit the export form and verify response.
     $this->drupalPostForm('admin/config/development/configuration/full/export', array(), t('Export'));
     $this->assertResponse(200, 'User can access the download callback.');
     // Test if header contains file name with hostname and timestamp.
     $request = \Drupal::request();
     $hostname = str_replace('.', '-', $request->getHttpHost());
     $header_content_disposition = $this->drupalGetHeader('content-disposition');
     $header_match = (bool) preg_match('/attachment; filename="config-' . preg_quote($hostname) . '-\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}\\.tar\\.gz"/', $header_content_disposition);
     $this->assertTrue($header_match, "Header with filename matches the expected format.");
     // Get the archived binary file provided to user for download.
     $archive_data = $this->getRawContent();
     // Temporarily save the archive file.
     $uri = file_unmanaged_save_data($archive_data, 'temporary://config.tar.gz');
     // Extract the archive and verify it's not empty.
     $file_path = file_directory_temp() . '/' . file_uri_target($uri);
     $archiver = new Tar($file_path);
     $archive_contents = $archiver->listContents();
     $this->assert(!empty($archive_contents), 'Downloaded archive file is not empty.');
     // Prepare the list of config files from active storage, see
     // \Drupal\config\Controller\ConfigController::downloadExport().
     $storage_active = $this->container->get('config.storage');
     $config_files = array();
     foreach ($storage_active->listAll() as $config_name) {
         $config_files[] = $config_name . '.yml';
     }
     // Assert that the downloaded archive file contents are the same as the test
     // site active store.
     $this->assertIdentical($archive_contents, $config_files);
     // Ensure the test configuration override is in effect but was not exported.
     $this->assertIdentical(\Drupal::config('system.maintenance')->get('message'), 'Foo');
     $archiver->extract(file_directory_temp(), array('system.maintenance.yml'));
     $file_contents = file_get_contents(file_directory_temp() . '/' . 'system.maintenance.yml');
     $exported = Yaml::decode($file_contents);
     $this->assertNotIdentical($exported['message'], 'Foo');
     // Check the single export form doesn't have "form-required" elements.
     $this->drupalGet('admin/config/development/configuration/single/export');
     $this->assertNoRaw('js-form-required form-required', 'No form required fields are found.');
     // Ensure the temporary file is not available to users without the
     // permission.
     $this->drupalLogout();
     $this->drupalGet('system/temporary', ['query' => ['file' => 'config.tar.gz']]);
     $this->assertResponse(403);
 }
Exemple #14
0
function ophir_copy_file($from, $to)
{
    if (function_exists('file_unmanaged_copy')) {
        $filename = file_unmanaged_save_data(file_get_contents($from), $to, FILE_EXISTS_REPLACE);
        return $filename ? file_create_url($filename) : false;
    } else {
        if (file_exists($to)) {
            if (crc32(file_get_contents($from)) === crc32(file_get_contents($from))) {
                return $to;
            }
            $i = pathinfo($to);
            $to = $i['dirname'] . '/' . $i['filename'] . time() . '.' . $i['extension'];
        }
        return copy($from, $to) ? $to : FALSE;
    }
}
 /**
  * Test the file_unmanaged_save_data() function.
  */
 function testFileSaveData()
 {
     $contents = $this->randomMachineName(8);
     $this->settingsSet('file_chmod_file', 0777);
     // No filename.
     $filepath = file_unmanaged_save_data($contents);
     $this->assertTrue($filepath, 'Unnamed file saved correctly.');
     $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
     $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
     // Provide a filename.
     $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
     $this->assertTrue($filepath, 'Unnamed file saved correctly.');
     $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
     $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
     $this->assertFilePermissions($filepath, 0777);
 }
Exemple #16
0
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @param $form
 *   The form.
 * @param $form_state
 *   The form state.
 */
function adminimal_form_system_theme_settings_alter(&$form, &$form_state)
{
    // Get adminimal theme path.
    global $base_url;
    $adminimal_path = drupal_get_path('theme', 'adminimal');
    $old_css_path = $adminimal_path . '/css/custom.css';
    $custom_css_path = 'public://adminimal-custom.css';
    $custom_css_dir = str_replace($base_url . '/', "", file_create_url($custom_css_path));
    $custom_css_url = file_create_url($custom_css_path);
    // Try to create the adminimal-custom.css file automatically.
    if (!file_exists($custom_css_path)) {
        // Try to migrate from the old css.
        if (file_exists($old_css_path)) {
            file_unmanaged_copy($old_css_path, $custom_css_path, FILE_EXISTS_ERROR);
        } else {
            file_unmanaged_save_data("", $custom_css_path, FILE_EXISTS_ERROR);
        }
    }
    // Notify user to remove his old css file.
    if (file_exists($old_css_path)) {
        drupal_set_message(t('Please delete the old @css_location file, as its no longer used.', array('@css_location file' => $old_css_path)), 'warning');
    }
    $form['adminimal_custom'] = array('#type' => 'fieldset', '#title' => t('Adminimal Customization'), '#weight' => -10);
    $form['skin'] = array('#type' => 'fieldset', '#title' => t('Adminimal skin'), '#weight' => -11);
    // Create the select list.
    $form['skin']['adminimal_theme_skin'] = array('#type' => 'select', '#title' => t('Skin selection'), '#default_value' => theme_get_setting('adminimal_theme_skin'), '#options' => array('default' => t('Adminimal Default'), 'material' => t('Material (BETA version)'), 'alternative' => t('Alternative')), '#description' => t('Select desired skin style. Note that this feature is in beta stage and there might be some issues.'), '#required' => FALSE);
    $form['adminimal_custom']['style_checkboxes'] = array('#type' => 'checkbox', '#title' => t('Style checkboxes and radio buttons in Webkit browsers.'), '#description' => t('Enabling this option will style checkbox and radio buttons for Webkit browsers like Google Chrome, Safari, Opera and their mobile versions.
     Enabling this option will <strong>not</strong> have any negative impact on older browsers that dont support pure CSS styling of checkboxes like Internet Explorer or Firefox.'), '#default_value' => theme_get_setting('style_checkboxes'));
    $form['adminimal_custom']['display_icons_config'] = array('#type' => 'checkbox', '#title' => t('Display icons in Configuration page'), '#default_value' => theme_get_setting('display_icons_config'));
    $form['adminimal_custom']['rounded_buttons'] = array('#type' => 'checkbox', '#title' => t('Use rounded buttons'), '#description' => t('Uncheck this setting if you dont like the rounded button styling for some action links'), '#default_value' => theme_get_setting('rounded_buttons'));
    $form['adminimal_custom']['sticky_actions'] = array('#type' => 'checkbox', '#title' => t('Sticky form actions'), '#description' => t('This will make the form actions div fixed bottom positioning. So for example when you visit the node edit page you wont need to scroll down to save/preview/delete the node. The form action buttons will be sticky to the bottom of the screen.'), '#default_value' => theme_get_setting('sticky_actions'));
    $form['adminimal_custom']['avoid_custom_font'] = array('#type' => 'checkbox', '#title' => t('Avoid using "Open Sans" font'), '#description' => t('(useful for languages that are not well supported by the "Open sans" font. Like Japanese for example)'), '#default_value' => theme_get_setting('avoid_custom_font'));
    $form['adminimal_custom']['adminimal_ckeditor'] = array('#type' => 'checkbox', '#title' => t('CKEditor support'), '#description' => t('Loads custom adminimal css skin for CKEditor. Disable this to avoid css conflicts when using other CKEditor skins.'), '#default_value' => theme_get_setting('adminimal_ckeditor'));
    $form['adminimal_custom']['use_custom_media_queries'] = array('#type' => 'checkbox', '#title' => t('Use Custom Media Queries'), '#description' => t('You can override the mobile and tablet media queries from this option. Use it only if you know what media queries are and how to use them.'), '#default_value' => theme_get_setting('use_custom_media_queries'));
    $form['adminimal_custom']['media_queries'] = array('#type' => 'fieldset', '#title' => t('Custom Media Queries'), '#states' => array('visible' => array(':input[name="use_custom_media_queries"]' => array('checked' => TRUE))));
    $form['adminimal_custom']['media_queries']['media_query_mobile'] = array('#type' => 'textfield', '#title' => t('Mobile media query'), '#description' => t('The media query to load the mobile.css styles.'), '#default_value' => theme_get_setting('media_query_mobile'));
    $form['adminimal_custom']['media_queries']['media_query_tablet'] = array('#type' => 'textfield', '#title' => t('Tablet media query'), '#description' => t('The media query to load the tablet.css styles.'), '#default_value' => theme_get_setting('media_query_tablet'));
    $form['adminimal_custom']['custom_css'] = array('#type' => 'checkbox', '#title' => t('Use "adminimal-custom.css"'), '#description' => t('Include adminimal-custom.css file to override or add custom css code without subthememing/hacking Adminimal Theme.'), '#default_value' => theme_get_setting('custom_css'));
    $form['adminimal_custom']['adminimal_custom_check'] = array('#type' => 'fieldset', '#title' => t('Custom CSS file check'), '#weight' => 50, '#states' => array('visible' => array(':input[name="custom_css"]' => array('checked' => TRUE))));
    if (file_exists($custom_css_path)) {
        $form['adminimal_custom']['adminimal_custom_check']['custom_css_description'] = array('#markup' => t('Custom CSS file Found in: !css', array('!css' => "<span class='css_path'>" . $custom_css_dir . "</span>")), '#prefix' => '<div class="messages status custom_css_found">', '#suffix' => '</div>');
    } else {
        $form['adminimal_custom']['adminimal_custom_check']['custom_css_not_found'] = array('#markup' => t('Custom CSS file not found. You must create the !css file manually.', array('!css' => "<span class='css_path'>" . $custom_css_dir . "</span>")), '#prefix' => '<div class="messages error custom_css_not_found">', '#suffix' => '</div>');
    }
}
Exemple #17
0
 function complie($file = null)
 {
     $update = false;
     $theme_path = drupal_get_path('theme', $this->theme->theme);
     //print $theme_path.'<br>'.DRUPAL_ROOT.'<br/>';
     //print file_create_url($file).'<br/>';
     $assets_path = file_create_url($theme_path . '/assets');
     //$theme_url = url('<front>',array('absolute'=>true)).str_replace($GLOBALS['base_url'],'',$theme_path);
     //print url('<front>',array('absolute'=>true)).'<br/>';
     //print url('<front>',array('absolute'=>false)).'<br/>';
     //print $theme_path;die;
     //$assets_path = $theme_url . '/assets';
     //$assets_path = str_replace('//','/',$assets_path);
     $drupalexp_assets = variable_get('drupalexp_assets_path', '');
     if ($drupalexp_assets != $assets_path) {
         $update = true;
         variable_set('drupalexp_assets_path', $assets_path);
     }
     $ftime = $this->filetime($file);
     if (!empty($this->theme->lessc)) {
         foreach ($this->theme->lessc as $lessc_file) {
             if ($ftime < $this->filetime($lessc_file)) {
                 $update = true;
             }
             $this->output .= "@import \"{$lessc_file}\";\n";
         }
     }
     if ($update) {
         try {
             $this->css = $this->lessc->compile($this->output);
         } catch (exception $e) {
             drupal_set_message("fatal error: " . $e->getMessage(), 'error');
             return FALSE;
         }
         if ($file) {
             $css_output = "/*This file is generated by less css (http://lesscss.org) using drupalexp framework (http://drupalexp.com)*/\n/*Please do not modify this file content*/\n" . $this->css;
             $css_output = str_replace(array('../'), $assets_path . '/', $css_output);
             file_unmanaged_save_data($css_output, $file, FILE_EXISTS_REPLACE);
         }
     }
     return $this->css;
 }
 /**
  * {@inheritdoc}
  */
 public function denormalize($data, $class, $format = NULL, array $context = array())
 {
     // File content can be passed base64 encoded in a special "data" property.
     // That property is not a field, so we remove it before denormalizing the
     // rest of the file entity.
     $file_data = $data['data'][0]['value'];
     unset($data['data']);
     $entity = parent::denormalize($data, $class, $format, $context);
     // Decode and save to file if it's a new file.
     if (!isset($context['request_method']) || $context['request_method'] != 'patch') {
         $file_contents = base64_decode($file_data);
         $dirname = $this->fileSystem->dirname($entity->getFileUri());
         file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
         if ($uri = file_unmanaged_save_data($file_contents, file_build_uri(drupal_basename($entity->getFilename())))) {
             $entity->setFileUri($uri);
         } else {
             throw new RuntimeException('failed to write ' . $entity->getFilename());
         }
     }
     return $entity;
 }
 function complie($file = null)
 {
     $update = false;
     $theme_path = drupal_get_path('theme', $this->theme->theme);
     $assets_path = file_create_url($theme_path . '/assets');
     $config = \Drupal::service('config.factory')->getEditable('innovation.settings');
     if ($config->get('updated')) {
         $update = true;
     }
     $ftime = $this->filetime($file);
     if (!empty($this->theme->lessc)) {
         foreach ($this->theme->lessc as $lessc_file) {
             if ($ftime < $this->filetime($lessc_file)) {
                 $update = true;
             }
             $this->output .= "@import \"{$lessc_file}\";\n";
         }
     }
     if ($update) {
         $this->__setupFonts();
         if (!empty($this->google_fonts)) {
             $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
             $this->output = '@import url(' . $protocol . '://fonts.googleapis.com/css?family=' . implode('|', $this->google_fonts) . ');' . $this->output;
         }
         try {
             $this->css = $this->lessc->compile($this->output);
         } catch (exception $e) {
             drupal_set_message("fatal error: " . $e->getMessage(), 'error');
             return FALSE;
         }
         if ($file) {
             $css_output = "/*This file is generated by less css (http://lesscss.org) */\n/*Please do not modify this file content. It will be generated again when you change style*/\n" . $this->css;
             $css_output = str_replace(array('../'), $assets_path . '/', $css_output);
             file_unmanaged_save_data($css_output, $file, FILE_EXISTS_REPLACE);
         }
     }
     $config->set('updated', false);
     $config->save();
     return $this->css;
 }
Exemple #20
0
/**
 * @file
 * Save custom CSS to file
 */
function at_core_submit_login_block($values, $theme, $generated_files_path) {
  $login_block_css = '';

  // Set the heading font size.
  $font_size_px = '16px;';
  $font_size_rem = '1rem;';

  // Override if fonts extension is on and a default font size is set.
  if (isset($values['settings_enable_fonts']) && $values['settings_enable_fonts'] === 1) {
    if (!empty($values['settings_base_font_size'])) {
      $font_size_px = $values['settings_base_font_size'] . 'px;';
      //$font_size_rem = $values['settings_base_font_size'] / $values['settings_base_font_size'] . 'rem;';
    }
  }

  $login_block_css = ".block-login--horizontal .block__title{font-size:$font_size_px;font-size:$font_size_rem;}.block-login--horizontal .block__title,.block-login--horizontal > div,.block-login--horizontal .user-login-form,.block-login--horizontal .user-login-form > div,.block-login--horizontal .form-item,.block-login--horizontal .form-actions{display:inline-block;}";

  //$file_name = $theme . '.login-block.css';

  $file_name = 'login-block.css';

  $filepath = $generated_files_path . '/' . $file_name;
  file_unmanaged_save_data($login_block_css, $filepath, FILE_EXISTS_REPLACE);
}
Exemple #21
0
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @param $form
 *   The form.
 * @param $form_state
 *   The form state.
 */
function adminimal_form_system_theme_settings_alter(&$form, &$form_state)
{
    // Get adminimal theme path.
    global $base_url;
    $adminimal_path = drupal_get_path('theme', 'adminimal');
    $old_css_path = $adminimal_path . '/css/custom.css';
    $custom_css_path = 'public://adminimal-custom.css';
    $custom_css_dir = str_replace($base_url . '/', "", file_create_url($custom_css_path));
    $custom_css_url = file_create_url($custom_css_path);
    // Try to create the adminimal-custom.css file automatically.
    if (!file_exists($custom_css_path)) {
        // Try to migrate from the old css.
        if (file_exists($old_css_path)) {
            file_unmanaged_copy($old_css_path, $custom_css_path, FILE_EXISTS_ERROR);
        } else {
            file_unmanaged_save_data("", $custom_css_path, FILE_EXISTS_ERROR);
        }
    }
    // Notify user to remove his old css file.
    if (file_exists($old_css_path)) {
        drupal_set_message(t('Please delete the old @css_location file, as its no longer used.', array('@css_location file' => $old_css_path)), 'warning');
    }
    $form['adminimal_custom'] = array('#type' => 'fieldset', '#title' => t('Adminimal Customization'), '#weight' => -10);
    $form['adminimal_custom']['display_icons_config'] = array('#type' => 'checkbox', '#title' => t('Display icons in Configuration page'), '#default_value' => theme_get_setting('display_icons_config'));
    $form['adminimal_custom']['use_custom_media_queries'] = array('#type' => 'checkbox', '#title' => t('Use Custom Media Queries'), '#description' => t('You can override the mobile and tablet media queries from this option. Use it only if you know what media queries are and how to use them.'), '#default_value' => theme_get_setting('use_custom_media_queries'));
    $form['adminimal_custom']['media_queries'] = array('#type' => 'fieldset', '#title' => t('Custom Media Queries'), '#states' => array('visible' => array(':input[name="use_custom_media_queries"]' => array('checked' => TRUE))));
    $form['adminimal_custom']['media_queries']['media_query_mobile'] = array('#type' => 'textfield', '#title' => t('Mobile media query'), '#description' => t('The media query to load the mobile.css styles.'), '#default_value' => theme_get_setting('media_query_mobile'));
    $form['adminimal_custom']['media_queries']['media_query_tablet'] = array('#type' => 'textfield', '#title' => t('Tablet media query'), '#description' => t('The media query to load the tablet.css styles.'), '#default_value' => theme_get_setting('media_query_tablet'));
    $form['adminimal_custom']['custom_css'] = array('#type' => 'checkbox', '#title' => t('Use "adminimal-custom.css"'), '#description' => t('Include adminimal-custom.css file to override or add custom css code without subthememing/hacking Adminimal Theme.'), '#default_value' => theme_get_setting('custom_css'));
    $form['adminimal_custom']['adminimal_custom_check'] = array('#type' => 'fieldset', '#title' => t('Custom CSS file check'), '#weight' => 50, '#states' => array('visible' => array(':input[name="custom_css"]' => array('checked' => TRUE))));
    if (file_exists($custom_css_path)) {
        $form['adminimal_custom']['adminimal_custom_check']['custom_css_description'] = array('#markup' => t('Custom CSS file Found in: !css', array('!css' => "<span class='css_path'>" . $custom_css_dir . "</span>")), '#prefix' => '<div class="messages status custom_css_found">', '#suffix' => '</div>');
    } else {
        $form['adminimal_custom']['adminimal_custom_check']['custom_css_not_found'] = array('#markup' => t('Custom CSS file not found. You must create the !css file manually.', array('!css' => "<span class='css_path'>" . $custom_css_dir . "</span>")), '#prefix' => '<div class="messages error custom_css_not_found">', '#suffix' => '</div>');
    }
}
function at_core_submit_fonts($values, $generated_files_path)
{
    // Websafe fonts.
    $websafe_fonts = $values['websafe_options'];
    // Elements to apply fonts to.
    $font_elements = font_elements();
    // Fallback family
    $fallback_font_family = 'sans-serif';
    if (isset($values['settings_font_fallback'])) {
        $fallback_font_family = str_replace('_', '-', $values['settings_font_fallback']);
    }
    // Initialize some variables.
    $fonts = array();
    $base_size = '16';
    // 16px default
    // Inject config settings for web-fonts.
    $values['settings_font_use_google_fonts'] = FALSE;
    $values['settings_font_use_typekit'] = FALSE;
    $font_styles = array();
    foreach ($font_elements as $font_key => $font_values) {
        // Get the selectors for each element.
        $fonts[$font_key]['selectors'] = $font_values['selector'];
        // Reset the selectors variable if we have custom selectors.
        if ($font_key == 'custom_selectors' && !empty($values['settings_font_custom_selectors']) && !empty($values['settings_custom_selectors'])) {
            $fonts[$font_key]['selectors'] = $values['settings_custom_selectors'];
            // ? $values['settings_custom_selectors'] : 'ruby ruby'
        }
        // Size/Line height.
        if (!empty($values['settings_font_size_' . $font_key])) {
            //$base_size = $values['settings_font_size_base'] ? $values['settings_font_size_base'] : $base_size;
            $px_size = $values['settings_font_size_' . $font_key];
            $rem_size = $values['settings_font_size_' . $font_key] / $base_size;
            // line-height multipliers are a bit magical, but "pretty good" defaults.
            $line_height_multiplier = $values['settings_font_line_height_multiplier_default'];
            if ($px_size >= $values['settings_font_line_height_multiplier_large_size']) {
                $line_height_multiplier = $values['settings_font_line_height_multiplier_large'];
            }
            $fonts[$font_key]['size'] = ' font-size: ' . ceil($px_size) . 'px; font-size: ' . round($rem_size, 3) . 'rem;';
            $fonts[$font_key]['line_height'] = ' line-height: ' . ceil($px_size * $line_height_multiplier) . 'px; line-height: ' . round($rem_size * $line_height_multiplier, 3) . 'rem;';
            //      if (isset($values['settings_font_size_base'])) {
            //        $rem_size =  $base_size / 16;
            //        $fonts['base']['size'] = ' font-size: ' . ceil($px_size) . 'px; font-size: ' . round($rem_size, 3) . 'rem;';
            //        $fonts['base']['line_height'] = ' line-height: ' . ceil($px_size * $line_height_multiplier) . 'px; line-height: ' . round($rem_size * $line_height_multiplier, 3) . 'rem;';
            //      }
        }
        // Set font family for each key.
        if (isset($values['settings_font_' . $font_key])) {
            // Websafe.
            if ($values['settings_font_' . $font_key] == 'websafe') {
                if (isset($values['settings_font_websafe_' . $font_key])) {
                    if (!empty($websafe_fonts[$values['settings_font_websafe_' . $font_key]])) {
                        $websafe_font = $websafe_fonts[$values['settings_font_websafe_' . $font_key]];
                        $fonts[$font_key]['family'] = 'font-family: ' . trim($websafe_font) . ';';
                    } else {
                        $fonts[$font_key]['family'] = 'font-family: inherit;';
                    }
                } else {
                    $fonts[$font_key]['family'] = 'font-family: inherit;';
                }
            }
            // Google.
            if ($values['settings_font_' . $font_key] == 'google') {
                if (isset($values['settings_font_google_' . $font_key])) {
                    $fonts[$font_key]['family'] = 'font-family: ' . $values['settings_font_google_' . $font_key] . ', ' . trim($fallback_font_family) . ';';
                    $values['settings_font_use_google_fonts'] = TRUE;
                } else {
                    $fonts[$font_key]['family'] = 'font-family: inherit;';
                }
            }
            // Typekit.
            if ($values['settings_font_' . $font_key] == 'typekit') {
                if (!empty($values['settings_font_typekit_' . $font_key])) {
                    $fonts[$font_key]['family'] = 'font-family: ' . $values['settings_font_typekit_' . $font_key] . ', ' . trim($fallback_font_family) . ';';
                    $values['settings_font_use_typekit'] = TRUE;
                } else {
                    $fonts[$font_key]['family'] = 'font-family: inherit;';
                }
            }
        }
        // Font smoothing.
        if (isset($values['settings_font_smoothing_' . $font_key]) && $values['settings_font_smoothing_' . $font_key] == 1) {
            $fonts[$font_key]['smoothing'] = ' -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;';
        }
    }
    // Output data to file.
    if (!empty($fonts)) {
        foreach ($fonts as $font_key => $font_values) {
            if (isset($font_values['family']) || isset($font_values['size'])) {
                $font_style = $font_values['selectors'] . ' { ';
                if (isset($font_values['family'])) {
                    $font_style .= str_replace(';;', ';', $font_values['family']);
                }
                if (isset($font_values['size'])) {
                    $font_style .= $font_values['size'];
                }
                if (isset($font_values['line_height'])) {
                    $font_style .= $font_values['line_height'];
                }
                if (isset($font_values['smoothing'])) {
                    $font_style .= $font_values['smoothing'];
                }
                $font_style .= ' }';
                $font_styles[] = $font_style;
            }
        }
        $output = implode("\n", $font_styles);
    }
    $output = $output ? Xss::filter($output) : '/** No fonts styles set **/';
    $file_name = 'fonts.css';
    $filepath = "{$generated_files_path}/{$file_name}";
    file_unmanaged_save_data($output, $filepath, FILE_EXISTS_REPLACE);
    // Return modified values to convert to config.
    return $values;
}
    /**
     * Creates a valid but empty OPML file.
     *
     * @return string
     *   Path to empty OPML file.
     */
    public function getEmptyOpml()
    {
        $opml = <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<opml version="1.0">
  <head></head>
  <body>
    <outline text="Sample text" />
    <outline text="Sample text" url="Sample URL" />
  </body>
</opml>
EOF;
        $path = 'public://empty-opml.xml';
        return file_unmanaged_save_data($opml, $path);
    }
Exemple #24
0
 /**
  * Imports data for a provider that was manually uploaded in theme settings.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 private function importProviderData(FormStateInterface $form_state)
 {
     if ($form_state->getValue('clicked_button') === t('Save provider data')->render()) {
         $provider_path = ProviderManager::FILE_PATH;
         file_prepare_directory($provider_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
         $provider = $form_state->getValue('cdn_provider', $this->theme->getSetting('cdn_provider'));
         $file = "{$provider_path}/{$provider}.json";
         if ($import_data = $form_state->getValue('cdn_provider_import_data', FALSE)) {
             file_unmanaged_save_data($import_data, $file, FILE_EXISTS_REPLACE);
         } elseif ($file && file_exists($file)) {
             file_unmanaged_delete($file);
         }
         // Clear the cached definitions so they can get rebuilt.
         $this->providerManager->clearCachedDefinitions();
     }
 }
Exemple #25
0
 public function outputFile($file, $force = FALSE)
 {
     $update = FALSE;
     $theme_path = drupal_get_path('theme', $this->theme->theme);
     $theme_path = file_create_url($theme_path);
     $theme_url = url('<front>') . str_replace($GLOBALS['base_url'], '', $theme_path);
     $assets_path = $theme_url;
     $assets_path = str_replace('//', '/', $assets_path);
     $drupalexp_assets = variable_get('superhero_assets_path', '');
     if ($drupalexp_assets != $assets_path) {
         $update = true;
         variable_set('superhero_assets_path', $assets_path);
     }
     if (file_exists($file) && !$force) {
         $last_modified = filemtime($file);
         if (!empty($this->theme->scss)) {
             foreach ($this->theme->scss as $scss) {
                 $path = $this->theme_path . '/scss/' . $scss;
                 if (filemtime($path) > $last_modified) {
                     $update = TRUE;
                     break;
                 }
             }
         }
     } else {
         $update = TRUE;
     }
     if ($update) {
         if ($this->css == '') {
             $this->compileScss();
         }
         $this->css = str_replace(array('../'), $assets_path . '/', $this->css);
         $file_update = file_unmanaged_save_data($this->css, $file, FILE_EXISTS_REPLACE);
         if (!$file_update) {
             return FALSE;
         }
     }
     return $file;
 }
Exemple #26
0
/**
 * @file
 * Output formatted CSS for fonts.
 */

function at_core_submit_fonts($values, $theme, $generated_files_path) {

  // Paths
  $subtheme_path = drupal_get_path('theme', $theme);
  $generated_scripts_path = $subtheme_path . '/scripts/generated';

  // Websafe fonts.
  $websafe_fonts = websafe_fonts();

  // Elements to apply fonts to.
  $font_elements = font_elements();

  // Initialize some variables.
  $fonts = array();
  $size = '';
  $base_size = '16'; // 16px default
  $px_size = '';
  $rem_size = '';

  $fileOperations = new FileOperations();
  $font_styles = array();

  foreach ($font_elements as $font_key => $font_values) {

    // Get the selectors for each element.
    $fonts[$font_key]['selectors'] = $font_values['selector'];

    // Custom selectors, reset the selectors variable if we have custom selectors.
    if ($font_key == 'custom_selectors' && !empty($values['settings_font_custom_selectors']) && !empty($values['settings_custom_selectors'])) {
      $fonts[$font_key]['selectors'] = $values['settings_custom_selectors']; // ? $values['settings_custom_selectors'] : 'ruby ruby'
    }

    // Size/Line height
    if (!empty($values['settings_font_size_' . $font_key])) {

      $px_size = $values['settings_font_size_' . $font_key];
      $rem_size = $values['settings_font_size_' . $font_key] / $base_size;

      // line-height multipliers are a bit magical, but "pretty good" defaults.
      $line_height_multiplier = $values['settings_font_lineheight_multiplier_default'];
      if ($px_size >= $values['settings_font_lineheight_multiplier_large_size']) {
        $line_height_multiplier = $values['settings_font_lineheight_multiplier_large'];
      }

      $fonts[$font_key]['size'] = 'font-size:' . ceil($px_size) . 'px; font-size:' . round($rem_size, 3) . 'rem;';
      $fonts[$font_key]['lineheight'] = 'line-height:' . ceil($px_size * $line_height_multiplier) . 'px; line-height:' . round($rem_size * $line_height_multiplier, 3) . 'rem;';
    }

    // Websafe
    if ($values['settings_font_' . $font_key] == 'websafe') {
      $fonts[$font_key]['family'] = 'font-family:' . $websafe_fonts[$values['settings_font_websafe']] . ';';
    }

    // Customstack
    if ($values['settings_font_' . $font_key] == 'customstack') {
      $fonts[$font_key]['family'] = 'font-family:' . $values['settings_font_customstack'] . ';';
    }

    // Google
    if ($values['settings_font_' . $font_key] == 'google') {
      $fonts[$font_key]['family'] = 'font-family:' . $values['settings_font_google_' . $font_key] . ';';
    }

    // Typekit
    if ($values['settings_font_' . $font_key] == 'typekit') {
      $fonts[$font_key]['family'] = 'font-family:' . $values['settings_font_typekit_' . $font_key] . ';';
    }
  }

  // Output data to file
  if (!empty($fonts)) {
    foreach ($fonts as $key => $values) {
      if (isset($values['family']) || isset($values['size'])) {
        $font_style = $values['selectors'] . '{';

        if (isset($values['family'])) {
          $font_style .= $values['family'];
        }

        if (isset($values['size'])) {
          $font_style .= $values['size'];
        }

        if (isset($values['lineheight'])) {
          $font_style .= $values['lineheight'];
        }

        $font_style .= '}';
        $font_styles[] = $font_style;
      }
    }

    $output = implode("\n", $font_styles);
  }

  $output = $output ? Xss::filter($output) : '/** No fonts styles set **/';

  //$file_name = $theme . '.fonts.css';

  $file_name = 'fonts.css';
  $filepath = "$generated_files_path/$file_name";
  file_unmanaged_save_data($output, $filepath, FILE_EXISTS_REPLACE);
}
Exemple #27
0
/**
 * @file
 * Generate title styles.
 */
function at_core_submit_titles($values, $theme, $generated_files_path) {
  $titles_styles = array();

  // Array of valid title types
  $titles_valid_types = title_valid_type_options();

  // Get the font elements array.
  $font_elements = font_elements();
  $css = array();

  // Build arrays of selectors with associated styles.
  foreach ($font_elements as $font_element_key => $font_element_value) {
    if (in_array($font_element_key, $titles_valid_types)) {
      $case = 'text-transform:';
      $weight = 'font-weight:';
      $alignment = 'text-align:';
      // Selector
      if (!empty($font_element_value['selector'])) {
        $css[$font_element_key]['selector'] = $font_element_value['selector'];
      }

      //var_dump($values['settings_titles_' . $font_element_key . '_case']);

      // Case or Font variant: small-caps is a font-variant, set properties and values accordingly.
      // We need to set tranform and variant explicitly so selectors can override each other, without
      // any nasty inheritance issues, such as when .page__title overrides h1.
      if (!empty($values['settings_titles_' . $font_element_key . '_case'])) {
        if ($values['settings_titles_' . $font_element_key . '_case'] == 'small-caps') {
          $css[$font_element_key]['styles']['font_variant'] = 'font-variant:' . $values['settings_titles_' . $font_element_key . '_case'];
          $css[$font_element_key]['styles']['text_transform'] = 'text-transform:none';
        }
        else {
          $css[$font_element_key]['styles']['case'] = $case . $values['settings_titles_' . $font_element_key . '_case'];
          $css[$font_element_key]['styles']['font_variant'] = 'font-variant:normal';
        }
      }
      // Weight
      if (!empty($values['settings_titles_' . $font_element_key . '_weight'])) {
        $css[$font_element_key]['styles']['weight'] = $weight . $values['settings_titles_' . $font_element_key . '_weight'];
      }
      // Alignment
      if (!empty($values['settings_titles_' . $font_element_key . '_alignment'])) {
        $css[$font_element_key]['styles']['align'] = $alignment . $values['settings_titles_' . $font_element_key . '_alignment'];
      }
    }
  }

  // Format CSS.
  if (!empty($css)) {
    $output = array();
    foreach ($css as $selector_key => $selector_styles) {
      if (isset($selector_styles['styles'])) {
        $output[] = $selector_styles['selector'] . '{' .  implode(';', $selector_styles['styles']) . '}';
      }
    }
    if (!empty($output)) {
      // Output data to file.
      $titles_styles = implode("\n", $output);
      if (!empty($titles_styles)) {

        //$file_name = $theme . '.titles.css';

        $file_name = 'title-styles.css';

        $filepath = "$generated_files_path/$file_name";
        file_unmanaged_save_data($titles_styles, $filepath, FILE_EXISTS_REPLACE);
      }
    }
  }
}
 /**
  * Download the remote thumbnail to the local file system.
  */
 protected function downloadThumbnail()
 {
     $local_uri = $this->getLocalThumbnailUri();
     if (!file_exists($local_uri)) {
         $thumb_dir = $this->getUploadLocation();
         file_prepare_directory($thumb_dir, FILE_CREATE_DIRECTORY);
         $thumbnail = $this->httpClient->request('GET', $this->getRemoteThumbnailUrl());
         file_unmanaged_save_data((string) $thumbnail->getBody(), $local_uri);
     }
 }
Exemple #29
0
/**
 * Backup Theme Settings
 */
function md_boom_multi_backup_theme_settings()
{
    $theme_settings = variable_get('theme_md_boom_multi_settings');
    $current_time = time();
    $cv_datetime = date("Y-m-d", $current_time);
    $backup_file = serialize(base64_encode(drupal_json_encode($theme_settings)));
    $bu_folder = 'public://md_boom_multi_backup';
    if (file_prepare_directory($bu_folder) === false) {
        drupal_mkdir($bu_folder);
    }
    if (file_unmanaged_save_data($backup_file, $bu_folder . '/backup-' . $cv_datetime . '-' . $current_time . '.txt', FILE_EXISTS_REPLACE) === FALSE) {
        drupal_set_message(t("Could not create backup file."));
        return;
    } else {
        drupal_set_message(t("Backup Theme Settings Successful!"));
    }
}
 /**
  * {@inheritdoc}
  */
 public function getField(MediaInterface $media, $name)
 {
     $matches = $this->matchRegexp($media);
     if (!$matches['shortcode']) {
         return FALSE;
     }
     if ($name == 'shortcode') {
         return $matches['shortcode'];
     }
     // If we have auth settings return the other fields.
     if ($this->configuration['use_instagram_api'] && ($instagram = $this->fetchInstagram($matches['shortcode']))) {
         switch ($name) {
             case 'id':
                 if (isset($instagram->id)) {
                     return $instagram->id;
                 }
                 return FALSE;
             case 'type':
                 if (isset($instagram->type)) {
                     return $instagram->type;
                 }
                 return FALSE;
             case 'thumbnail':
                 if (isset($instagram->images->thumbnail->url)) {
                     return $instagram->images->thumbnail->url;
                 }
                 return FALSE;
             case 'thumbnail_local':
                 if (isset($instagram->images->thumbnail->url)) {
                     $local_uri = $this->configFactory->get('media_entity_instagram.settings')->get('local_images') . '/' . $matches['shortcode'] . '.' . pathinfo($instagram->images->thumbnail->url, PATHINFO_EXTENSION);
                     if (!file_exists($local_uri)) {
                         file_prepare_directory($local_uri, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
                         $image = file_get_contents($local_uri);
                         file_unmanaged_save_data($image, $local_uri, FILE_EXISTS_REPLACE);
                         return $local_uri;
                     }
                 }
                 return FALSE;
             case 'thumbnail_local_uri':
                 if (isset($instagram->images->thumbnail->url)) {
                     return $this->configFactory->get('media_entity_instagram.settings')->get('local_images') . '/' . $matches['shortcode'] . '.' . pathinfo($instagram->images->thumbnail->url, PATHINFO_EXTENSION);
                 }
                 return FALSE;
             case 'username':
                 if (isset($instagram->user->username)) {
                     return $instagram->user->username;
                 }
                 return FALSE;
             case 'caption':
                 if (isset($instagram->caption->text)) {
                     return $instagram->caption->text;
                 }
                 return FALSE;
             case 'tags':
                 if (isset($instagram->tags)) {
                     return implode(" ", $instagram->tags);
                 }
                 return FALSE;
         }
     }
     return FALSE;
 }