<?php
/**
 * @file
 * Panels Import.
 */

/**
 * Implement hook_ctools_plugin_api().
 */
function panels_import_ctools_plugin_api($module, $api) {
  if (($module == 'page_manager' && $api == 'pages_default')
    || ($module == 'panels_mini' && $api == 'panels_default')
    || ($module == 'ctools_custom_content' && $api == 'ctools_content')
    || ($module == 'pm_existing_pages' && $api == 'pm_existing_pages')) {
    return array('version' => 1);
  }
}

/**
 * Implementation of hook_pm_existing_pages_info()
 */
function panels_import_pm_existing_pages_info() {
  return _panels_import_load_defaults('page_manager', 'pm_existing_pages', 'pm_existing_page');
}

/**
 * Scans folder for files with ctools/panels default objects.
 *
 * @param string $module
 *   Name of module.
 * @param string $subfolder
 *   Name of subfolder to scan.
 * @param string $variable
 *   Primary object variable to add to array.
 *   For example, 'page' for files starting with "$page = new stdClass".
 *
 * @return array
 */
function _panels_import_load_defaults($module, $subfolder, $variable) {
  $imports_dir = 'sites/all/imports';

  $folder = "$imports_dir/$module/$subfolder";
  $files = file_scan_directory($folder, '/\.inc$/', array('recurse' => FALSE));

  $objects = array();
  foreach ($files as $file) {
    $object = _panels_import_fetch_default($file->uri, $variable);
    if ($object) {
      $objects[$object->name] = $object;
    }
  }

  return $objects;
}

/**
 * Includes file and returns object or NULL if file don't have an exported
 * object.
 * 
 * @param string $filename
 * @param string $variable
 *   Primary object variable to add to array.
 *   For example, 'page' for files starting with "$page = new stdClass".
 *
 * @return mixed
 *   Exported object or NULL.
 */
function _panels_import_fetch_default($uri, $variable) {
  ${$variable} = NULL;
  include $uri;
  if (${$variable} && ${$variable}->name) {
    return ${$variable};
  }
  else {
    return NULL;
  }
}
