<?php

/**
 * The name of the attribute used to store the thmr id.
 */
define ('DEVEL_THEMER_ATTRIBUTE', 'data-thmr');

/**
 * Implements hook_menu().
 */
function devel_themer_menu() {
  $items = array();

  $items['admin/config/development/devel_themer'] = array(
    'title' => 'Devel Themer',
    'description' => 'Display or hide the textual template log',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('devel_themer_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['devel_themer/variables/%/%'] = array(
    'title' => 'Theme Development AJAX variables',
    'page callback' => 'devel_themer_ajax_variables',
    'page arguments' => array(2, 3),
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * A menu callback used by popup to retrieve variables from cache for a recent page.
 *
 * @param $request_id
 *   A unique key that is sent to the browser in Drupal.Settings.devel_themer_request_id
 * @param $call
 *   The theme call for which you wish to retrieve variables.
 * @return string
 * A chunk of HTML with the devel_print_object() rendering of the variables.
 */
function devel_themer_ajax_variables($request_id, $call) {
  $file = "temporary://devel_themer_$request_id";
  if ($data = unserialize(file_get_contents($file))) {
    $variables = $data[$call]['variables'];
    if (has_krumo()) {
      $content = krumo_ob($variables);
    }
    elseif ($data[$call]['type'] == 'func') {
      $content = $variables;
    }
    else {
      $content =  $variables;
    }
  }
  else {
    $content =  'Ajax variables file not found. -' . check_plain($file);
  }

  $commands[] = ajax_command_replace('div.themer-variables', '<div class="themer-variables">' . $content . '</div>');
  return array('#type' => 'ajax', '#commands' => $commands);
}

function devel_themer_admin_settings() {
  $form['devel_themer_log'] = array('#type' => 'checkbox',
    '#title' => t('Display theme log'),
    '#default_value' => variable_get('devel_themer_log', FALSE),
    '#description' => t('Display the list of theme templates and theme functions which could have been be used for a given page. The one that was actually used is bolded. This is the same data as the represented in the popup, but all calls are listed in chronological order and can alternately be sorted by time.'),
  );
  return system_settings_form($form);
}


function devel_themer_init() {
  if (user_access('access devel information')) {
    // Add requisite libraries.
    drupal_add_library('system', 'jquery.form');
    drupal_add_library('system', 'drupal.ajax');
    drupal_add_library('system', 'ui.draggable');
    drupal_add_library('system', 'ui.resizable');

    // Add this module's JS and CSS.
    $path = drupal_get_path('module', 'devel_themer');
    drupal_add_js($path . '/devel_themer.js');
    drupal_add_css($path . '/devel_themer.css');
    drupal_add_css($path . '/devel_themer_ie_fix.css', array(
      'browsers' => array('IE' => 'lt IE 7', '!IE' => FALSE),
      'media' => 'screen',
      'weight' => 20,
      'preprocess' => FALSE,
    ));

    // Add krumo JS and CSS. We can't rely on krumo automatically doing this,
    // because we add our HTML dynamically after initial page load.
    if (has_krumo()) {
      $path_to_devel = drupal_get_path('module', 'devel');
      // Krumo files don't work correctly when aggregated.
      drupal_add_js($path_to_devel . '/krumo/krumo.js', array('preprocess' => FALSE));
      drupal_add_css($path_to_devel . '/krumo/skins/default/skin.css', array('preprocess' => FALSE));
    }

    devel_themer_popup();

    if (!devel_silent() && variable_get('devel_themer_log', FALSE)) {
      register_shutdown_function('devel_themer_shutdown');
    }
  }
}

function devel_themer_shutdown() {
  print devel_themer_log();
}

/**
 * Show all theme templates and functions that could have been used on this page.
 */
function devel_themer_log() {
  if (isset($GLOBALS['devel_theme_calls'])) {
    foreach ($GLOBALS['devel_theme_calls'] as $counter => $call) {
      // Sometimes $call is a string.  Not sure why.
      if (is_array($call)) {
        $id = "devel_theme_log_link_$counter";
        $marker = "<div id=\"$id\" class=\"devel_theme_log_link\"></div>\n";

        $used = $call['used'];
        if ($call['type'] == 'func') {
          $name = $call['name'] . '()';
          foreach ($call['candidates'] as $item) {
            if ($item == $used) {
              $items[] = "<strong>$used</strong>";
            }
            else {
              $items[] = $item;
            }
          }
        }
        else {
          $name = $call['name'];
          foreach ($call['candidates'] as $item) {
            if ($item == basename($used)) {
              $items[] = "<strong>$used</strong>";
            }
            else {
              $items[] = $item;
            }
          }
        }
        $rows[] = array($call['duration'], $marker . $name, implode(', ', $items));
        unset($items);
      }
    }
    $header = array('Duration (ms)', 'Template/Function', "Candidate template files or function names");
    $output = theme('table', $header, $rows);
    return $output;
  }
}

/**
 * Implements hook_theme_registry_alter().
 *
 * Route all theme hooks to devel_themer_catch_function().
 */
function devel_themer_theme_registry_alter(&$theme_registry) {
  foreach ($theme_registry as $hook => $data) {
    if (isset($theme_registry[$hook]['function'])) {
      // If the hook is a function, store it so it can be run after it has been intercepted.
      // This does not apply to template calls.
      $theme_registry[$hook]['devel_function_intercept'] = $theme_registry[$hook]['function'];
    }
    // Add our catch function to intercept functions as well as templates.
    $theme_registry[$hook]['function'] = 'devel_themer_catch_function';

    // Remove the process and preprocess functions so they are
    // only called by devel_themer_theme_twin().
    $theme_registry[$hook]['devel_function_preprocess_intercept'] = isset($theme_registry[$hook]['preprocess functions']) ? $theme_registry[$hook]['preprocess functions'] : array();
    $theme_registry[$hook]['devel_function_process_intercept'] = isset($theme_registry[$hook]['process functions']) ? $theme_registry[$hook]['process functions'] : array();
    $theme_registry[$hook]['preprocess functions'] = array();
    $theme_registry[$hook]['process functions'] = array();
  }
}

/**
 * Implements hook_module_implements_alter().
 *
 * Ensure devel_themer_theme_registry_alter() runs as late as possible.
 */
function devel_themer_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'theme_registry_alter') {
    // Unsetting and resetting moves the item to the end of the array.
    $group = $implementations['devel_themer'];
    unset($implementations['devel_themer']);
    $implementations['devel_themer'] = $group;
  }
}

/**
 * Injects markers into the html returned by theme functions/templates.
 *
 * Uses simplehtmldom to add a thmr attribute to toplevel html elements.
 * A toplevel text element will be wrapped in a span.
 *
 * @param string $html
 * @param string $marker
 */
function devel_themer_inject_markers($html, $marker) {
  if (!module_exists('simplehtmldom')) {
    drupal_set_message(t('<a href="http://drupal.org/project/simplehtmldom">Simplehtmldom</a> module is missing and required by Theme developer.'), 'error', FALSE);
    return $html;
  }

  $html_dom = new simple_html_dom();
  $html_dom->load($html);
  foreach ($html_dom->root->nodes as $element) {
    if ($element->nodetype == HDOM_TYPE_TEXT) {
      if (trim($element->innertext) !== '') {
        $element->innertext = "<span " . DEVEL_THEMER_ATTRIBUTE . "='$marker' class='devel-themer-wrapper'>{$element->innertext}</span>";
      }
    }
    elseif ($element->hasAttribute(DEVEL_THEMER_ATTRIBUTE)) {
      $element->setAttribute(DEVEL_THEMER_ATTRIBUTE, "$marker " . $element->getAttribute(DEVEL_THEMER_ATTRIBUTE));
    }
    else {
      $element->setAttribute(DEVEL_THEMER_ATTRIBUTE, $marker);
    }
  }
  $html = (string)$html_dom;
  // Release memory.
  $html_dom->clear();
  unset($html_dom);
  return $html;
}

/**
 * Intercepts all theme calls (including templates), adds to template log, and dispatches to original theme function.
 */
function devel_themer_catch_function() {
  $trace = debug_backtrace(FALSE);
  $hook = $trace[1]['args'][0];
  if (sizeof($trace[1]['args']) > 1) {
    $variables =  $trace[1]['args'][1];
    if (!is_array($variables)) {
      watchdog('devel_themer', 'Variables should be passed as an associative array to the theme hook !hook.', array('!hook' => is_array($hook) ? implode(', ', $hook) : $hook), WATCHDOG_ERROR);
    }
  }
  else {
    $variables = array();
  }

  $counter = devel_counter();
  $variables['thmr_key'] = "thmr_" . $counter;
  $timer_name = "thmr_$counter";
  timer_start($timer_name);

  // The twin of theme(). All rendering done through here.
  list($return, $meta) = devel_themer_theme_twin($hook, $variables);
  $time = timer_stop($timer_name);

  if (!empty($return) && !is_array($return) && !is_object($return) && user_access('access devel information')) {
    $key = "thmr_$counter";

    // Check for themer attribute in content returned. Apply word boundaries so
    // that 'thmr_10' doesn't match 'thmr_1'.
    if (!preg_match("/\\b$key\\b/", $return)) {
      // Exclude wrapping a SPAN around content returned by theme functions
      // whose result is not intended for HTML usage.
      $exclude = array('options_none');

      // theme_html_tag() is a low-level theme function intended primarily for
      // markup added to the document HEAD.
      $exclude[] = 'html_tag';

      // DATE MODULE: Inline labels for date select lists shouldn't be wrapped.
      if (strpos($meta['hook'], 'date_part_label_') === 0 && $variables['element']['#type'] == 'date_select' && $variables['element']['#date_label_position'] == 'within') {
        $exclude[] = $hook;
      }

      if (!in_array($hook, $exclude)) {
        $return = devel_themer_inject_markers($return, $key);
      }
    }

    if ($meta['type'] == 'func') {
      $name = $meta['hook'];
      $used = $meta['used'];
      global $theme;
      $candidates = array();
      foreach (array_reverse($meta['suggestions']) as $suggestion) {
        $candidates[] = "{$theme}_{$suggestion}";
      }
      $candidates[] = "{$theme}_{$name}";
      if (empty($meta['variables'])) {
        $variables = array();
      }
    }
    else {
      $name = strtr($meta['hook'], '_', '-') . $meta['extension'];
      $candidates = array();
      foreach (array_reverse($meta['suggestions']) as $suggestion) {
        $candidates[] = strtr($suggestion, '_', '-') . $meta['extension'];
      }
      $candidates[] = $name;
      $used = $meta['used'];
    }


    // Set preprocessors.
    if (isset($meta['processor_functions']['preprocess functions'])) {
      $preprocessors = $meta['processor_functions']['preprocess functions'];
    }
    else {
      $preprocessors = array();
    }

    // Set processors.
    if (isset($meta['processor_functions']['process functions'])) {
      $processors = $meta['processor_functions']['process functions'];
    }
    else {
      $processors = array();
    }

    // This variable gets sent to the browser in Drupal.settings.
    $GLOBALS['devel_theme_calls'][$key] = array(
      'id' => $key,
      'name' => $name,
      'used' => $used,
      'type' => $meta['type'],
      'duration' => $time['time'],
      'candidates' => $candidates,
      'preprocessors' => $preprocessors,
      'processors' => $processors,
    );

    // Remove some things from variables to reduce size of item in crumo
    unset($meta['variables']['page']);

    // This variable gets serialized and cached on the server.
    $GLOBALS['devel_themer_server'][$key] = array(
      'variables' => $meta['variables'],
      'type' => $meta['type'],
    );
  }
  return $return;
}

/**
 * Nearly clones the Drupal API theme() function, but returns meta information in addition to the rendered output.
 *
 * Usage:
 * @code
 *   list($output, $meta) = devel_themer_theme_twin($hook, $variables);
 * @endcode
 *
 * @return
 *  An array with two items:
 *  - $output: The rendered HTML.
 *  - $meta: An associative array with the following keys:
 *    - 'wildcards': Candidate hooks which have been looked at but don't have
 *       an implementation.
 *    - 'hook': The first found hook with an implementation.
 *    - 'path': The path to the theme that implements $meta['hook'].
 *    @todo Document remaining keys.
 */
function devel_themer_theme_twin($hook, $variables) {
  static $hooks = NULL;
  $thmr_key = $variables['thmr_key'];
  unset($variables['thmr_key']);
  $meta = array();
  $meta['name'] = $hook;

  // If called before all modules are loaded, we do not necessarily have a full
  // theme registry to work with, and therefore cannot process the theme
  // request properly. See also _theme_load_registry().
  if (!module_load_all(NULL) && !defined('MAINTENANCE_MODE')) {
    throw new Exception(t('theme() may not be called until all modules are loaded.'));
  }

  if (!isset($hooks)) {
    drupal_theme_initialize();
    $hooks = theme_get_registry();
  }

  // If an array of hook candidates were passed, use the first one that has an
  // implementation.
  if (is_array($hook)) {
    foreach ($hook as $candidate) {
      if (isset($hooks[$candidate])) {
        break;
      }
      $meta['wildcards'][] = $candidate;
    }
    $hook = $candidate;
  }

  // If there's no implementation, check for more generic fallbacks. If there's
  // still no implementation, log an error and return an empty string.
  if (!isset($hooks[$hook])) {
    // Iteratively strip everything after the last '__' delimiter, until an
    // implementation is found.
    while ($pos = strrpos($hook, '__')) {
      $hook = substr($hook, 0, $pos);
      if (isset($hooks[$hook])) {
        break;
      }
      $meta['wildcards'][] = $hook;
    }
    if (!isset($hooks[$hook])) {
      // Only log a message when not trying theme suggestions ($hook being an
      // array).
      if (!isset($candidate)) {
        watchdog('theme', 'Theme key "@key" not found.', array('@key' => $hook), WATCHDOG_WARNING);
      }
      return array('', $meta);
    }
  }

  $meta['hook'] = $hook;
  $info = $hooks[$hook];
  $meta['path'] = isset($info['theme path']) ? $info['theme path'] : NULL;


  global $theme_path;
  $temp = $theme_path;
  // point path_to_theme() to the currently used theme path:
  $theme_path = isset($info['theme path']) ? $info['theme path'] : NULL;

  // Include a file if the theme function or variable processor is held elsewhere.
  if (!empty($info['includes'])) {
    foreach ($info['includes'] as $include_file) {
      include_once DRUPAL_ROOT . '/' . $include_file;
    }
  }

  // If a renderable array is passed as $variables, then set $variables to
  // the arguments expected by the theme function.
  if (isset($variables['#theme']) || isset($variables['#theme_wrappers'])) {
    $element = $variables;
    $variables = array();
    if (isset($info['variables'])) {
      foreach (array_keys($info['variables']) as $name) {
        if (isset($element["#$name"])) {
          $variables[$name] = $element["#$name"];
        }
      }
    }
    else {
      $variables[$info['render element']] = $element;
    }
  }

  // Merge in argument defaults.
  if (!empty($info['variables'])) {
    $variables += $info['variables'];
  }
  elseif (!empty($info['render element'])) {
    $variables += array($info['render element'] => array());
  }

  // Add the themer attribute here
  $variables['attributes_array'][DEVEL_THEMER_ATTRIBUTE] = $thmr_key;

  // Invoke the variable processors, if any. The processors may specify
  // alternate suggestions for which hook's template/function to use. If the
  // hook is a suggestion of a base hook, invoke the variable processors of
  // the base hook, but retain the suggestion as a high priority suggestion to
  // be used unless overridden by a variable processor function.
  if (isset($info['base hook'])) {
    $base_hook = $info['base hook'];
    $base_hook_info = $hooks[$base_hook];
    // Return the preprocessor functions to their original state
    $base_hook_info['preprocess functions'] = $base_hook_info['devel_function_preprocess_intercept'];
    $base_hook_info['process functions'] = $base_hook_info['devel_function_process_intercept'];
    if (isset($base_hook_info['preprocess functions']) || isset($base_hook_info['process functions'])) {
      $variables['theme_hook_suggestion'] = $hook;
      $hook = $base_hook;
      $info = $base_hook_info;
    }
  }
  $info['preprocess functions'] = $info['devel_function_preprocess_intercept'];
  $info['process functions'] = $info['devel_function_process_intercept'];
  if (isset($info['preprocess functions']) || isset($info['process functions'])) {
    $variables['theme_hook_suggestions'] = array();
    foreach (array('preprocess functions', 'process functions') as $phase) {
      if (!empty($info[$phase])) {
        foreach ($info[$phase] as $processor_function) {
          $meta['processor_functions'][$phase][] = $processor_function;
          if (function_exists($processor_function)) {
            // We don't want a poorly behaved process function changing $hook.
            $hook_clone = $hook;
            $processor_function($variables, $hook_clone);
          }
        }
      }
    }
    // If the preprocess/process functions specified hook suggestions, and the
    // suggestion exists in the theme registry, use it instead of the hook that
    // theme() was called with. This allows the preprocess/process step to
    // route to a more specific theme hook. For example, a function may call
    // theme('node', ...), but a preprocess function can add 'node__article' as
    // a suggestion, enabling a theme to have an alternate template file for
    // article nodes. Suggestions are checked in the following order:
    // - The 'theme_hook_suggestion' variable is checked first. It overrides
    //   all others.
    // - The 'theme_hook_suggestions' variable is checked in FILO order, so the
    //   last suggestion added to the array takes precedence over suggestions
    //   added earlier.
    $suggestions = array();
    if (!empty($variables['theme_hook_suggestions'])) {
      $suggestions = $variables['theme_hook_suggestions'];
    }
    if (!empty($variables['theme_hook_suggestion'])) {
      $suggestions[] = $variables['theme_hook_suggestion'];
    }
    foreach (array_reverse($suggestions) as $suggestion) {
      if (isset($hooks[$suggestion])) {
        $info = $hooks[$suggestion];
        break;
      }
    }
  }

  // Tidy up the theme things here.
  if (isset($info)) {
    unset($info['function']);
    if (isset($info['devel_function_intercept'])) {
      $info['function'] = $info['devel_function_intercept'];
    }
    $meta['hook'] = $hook;
    $meta['path'] = isset($info['theme path']) ? $info['theme path'] : NULL;
  }

  // Generate the output using either a function or a template.
  $output = '';
  if (isset($info['function'])) {
    if (function_exists($info['function'])) {
      $output = $info['function']($variables);
      $meta['type'] = 'func';
      $meta['used'] = $info['function'];
      $meta['suggestions'] = $suggestions;
    }
  }
  else {
    // Default render function and extension.
    $render_function = 'theme_render_template';
    $extension = '.tpl.php';

    // The theme engine may use a different extension and a different renderer.
    global $theme_engine;
    if (isset($theme_engine)) {
      if ($info['type'] != 'module') {
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
        }
        $extension_function = $theme_engine . '_extension';
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

    // In some cases, a template implementation may not have had
    // template_preprocess() run (for example, if the default implementation is
    // a function, but a template overrides that default implementation). In
    // these cases, a template should still be able to expect to have access to
    // the variables provided by template_preprocess(), so we add them here if
    // they don't already exist. We don't want to run template_preprocess()
    // twice (it would be inefficient and mess up zebra striping), so we use the
    // 'directory' variable to determine if it has already run, which while not
    // completely intuitive, is reasonably safe, and allows us to save on the
    // overhead of adding some new variable to track that.
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
      template_preprocess($default_template_variables, $hook);
      $variables += $default_template_variables;
    }

    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
    }
    $meta['type'] = 'tpl';
    $meta['used'] = $template_file;
    $meta['extension'] = $extension;
    $meta['suggestions'] = $suggestions;
    $meta['template_file'] = $template_file;
    $meta['preprocessors'] = isset($info['preprocess functions']) ? $info['preprocess functions'] : array();

    $output = $render_function($template_file, $variables);
  }
  $meta['variables'] = $variables;

  // restore path_to_theme()
  $theme_path = $temp;
  return array($output, $meta);
}

// We save the huge js array here instead of hook_footer so we can catch theme('page')
function devel_themer_exit() {
  // TODO: limit to html pages only $router_item = menu_get_item();
  //delivery_callback
  if (!empty($GLOBALS['devel_theme_calls']) && $_SERVER['REQUEST_METHOD'] != 'POST') {
    // A random string that is sent to the browser. It enables the popup to retrieve params/variables from this request.
    $request_id = uniqid(rand());
    // Write the variables information to the a file. It will be retrieved on demand via AJAX.
    // We used to write this to DB but was getting 'Warning: Got a packet bigger than 'max_allowed_packet' bytes'
    // Writing to temp dir means we don't worry about folder existence/perms and cleanup is free.
    try {
      $file = file_save_data(serialize($GLOBALS['devel_themer_server']), "temporary://devel_themer_$request_id", FILE_EXISTS_REPLACE);
    }
    catch (Exception $e) {
      $file = file_save_data(serialize(array("unables to save variables, probably due to pdo")), "temporary://devel_themer_$request_id", FILE_EXISTS_REPLACE);
    }

    // file_save_data() saves the file with permanent status. Change this to
    // temporary so that system_cron() garbage collects them.
    $file->status = 0;
    file_save($file);

    $GLOBALS['devel_theme_calls']['request_id'] = $request_id;
    $GLOBALS['devel_theme_calls']['devel_themer_uri'] = url("devel_themer/variables/$request_id");
    print '<script type="text/javascript">jQuery.extend(Drupal.settings, ' . drupal_json_encode($GLOBALS['devel_theme_calls']) . ");</script>\n";
  }
}

// just hand out next counter, or return current value
function devel_counter($increment = TRUE) {
  static $counter = 0;
  if ($increment) {
    $counter++;
  }
  return $counter;
}

/**
 * Return the popup template
 * placed here for easy editing
 */
function devel_themer_popup() {
  $majorver = substr(VERSION, 0, strpos(VERSION, '.'));

  // add translatable strings
  drupal_add_js(array('thmrStrings' =>
    array(
      'themer_info' => t('Themer info'),
      'toggle_throbber' => ' <img src="' . base_path() . drupal_get_path('module', 'devel_themer') . '/loader-little.gif' . '" alt="' . t('loading') . '" class="throbber" width="16" height="16" style="display:none" />',
      'parents' => t('Parents:') . ' ',
      'function_called' => t('Function called:') . ' ',
      'template_called' => t('Template called:') . ' ',
      'candidate_files' => t('Candidate template files:') . ' ',
      'preprocessors' => t('Preprocess functions:') . ' ',
      'processors' => t('Process functions:') . ' ',
      'candidate_functions' => t('Candidate function names:') . ' ',
      'drupal_api_docs' => t('link to Drupal API documentation'),
      'source_link_title' => t('link to source code'),
      'function_arguments' => t('Function Arguments'),
      'template_variables' => t('Template Variables'),
      'file_used' => t('File used:') . ' ',
      'duration' => t('Duration:') . ' ',
      'api_site' => variable_get('devel_api_site', 'http://api.drupal.org/'),
      'drupal_version' => $majorver,
      'source_link' => url('devel/source', array('query' => array('file' => ''))),
    ))
    , 'setting');

  $title = t('Drupal Themer Information');
  $intro = t('Click on any element to see information about the Drupal theme function or template that created it.');

  $popup = <<<EOT
  <div id="themer-fixeder">
  <div id="themer-relativer">
  <div id="themer-popup">
      <div class="topper">
        <span class="close">X</span> $title
      </div>
      <div id="parents" class="row">

      </div>
      <div class="info row">
        <div class="starter">$intro</div>
        <dl>
          <dt class="key-type">

          </dt>
          <dd class="key">

          </dd>
          <div class="used">
          </div>
          <dt class="candidates-type">

          </dt>
          <dd class="candidates">

          </dd>

          <dt class="preprocessors-type">

          </dt>
          <dd class="preprocessors">

          </dd>
          <dt class="processors-type">

          </dt>
          <dd class="processors">

          </dd>
          <div class="duration"></div>
        </dl>
      </div><!-- /info -->
      <div class="attributes row">
      <div class="themer-variables"></div>
      </div><!-- /attributes -->
    </div><!-- /themer-popup -->
    </div>
    </div>
EOT;

  drupal_add_js(array('thmr_popup' => $popup), 'setting');
}
