/**
  * Create the links on the dashboard page that will used to load the reports through ajax.
  * @param string $options An array to set options especially to display the default report_view configurations
  * @return boolean
  */
 public function displayReportLinks()
 {
     $user = new I2CE_User();
     $loggedin_role = $user->getRole();
     //for each of the views we display it directly to the dashboard page
     //get reports for the current user
     //I2CE::raiseMessage('opts ' . print_r($this->args,true));
     if (!array_key_exists('dashes', $this->args)) {
         $this->template->addFile("dashboard_missing.html");
         return;
     }
     if (array_key_exists('default_settings', $this->args)) {
         $defaults = $this->args['default_settings'];
     }
     $opt_settings = array('height' => 250, 'width' => 350, 'title' => '', 'label_size' => 10);
     foreach ($opt_settings as $key => $val) {
         if (!array_key_exists($key, $defaults)) {
             $defaults[$key] = $val;
         }
     }
     $dash = null;
     if (count($this->request_remainder) > 0) {
         $dash = array_shift($this->request_remainder);
     } else {
         $dash = $loggedin_role;
     }
     if (!array_key_exists($dash, $this->args['dashes'])) {
         $dash = 'default';
         if (!array_key_exists($dash, $this->args['dashes'])) {
             I2CE::raiseError("No default dashboard configured.");
             $this->template->addFile('dashboard_missing.html');
         }
     }
     $dash_details = $this->args['dashes'][$dash];
     $permissions = array();
     if (array_key_exists('tasks', $dash_details)) {
         $permissions[] = 'task(' . implode(',', $dash_details['tasks']) . ')';
     }
     if (array_key_exists('roles', $dash_details)) {
         $permissions[] = 'role(' . implode(',', $dash_details['roles']) . ')';
     }
     if (count($permissions) > 0 && !$this->hasPermission(implode('|', $permissions))) {
         $this->template->addFile("dashboard_denied.html");
         return;
     }
     if (array_key_exists('settings', $dash_details)) {
         foreach ($opt_settings as $key => $val) {
             if (array_key_exists($key, $dash_details['settings'])) {
                 $defaults[$key] = $dash_details['settings'][$key];
             }
         }
     }
     $this->template->setDisplayDataImmediate('dashboard_title', $defaults['title']);
     if (!array_key_exists('order', $dash_details) || !is_array($dash_details['order']) || count($dash_details['order']) == 0) {
         $this->template->addFile("dashboard_misconfigured.html");
         return;
     }
     $reportViews = $dash_details['order'];
     ksort($reportViews);
     $views = array();
     if (array_key_exists('report_views', $dash_details)) {
         $views = $dash_details['report_views'];
     }
     $reportListNode = $this->template->getElementById("dashboard_report_list");
     foreach ($reportViews as $report_view) {
         $view_settings = $defaults;
         if (array_key_exists($report_view, $views)) {
             if (array_key_exists('enabled', $views[$report_view]) && !$views[$report_view]['enabled']) {
                 // Skip if not enabled.
                 continue;
             }
             foreach ($opt_settings as $key => $val) {
                 if (array_key_exists($key, $views[$report_view]) && $views[$report_view][$key]) {
                     $view_settings[$key] = $views[$report_view][$key];
                 }
             }
         }
         $reportViewConfigs = I2CE::getConfig()->getAsArray("/modules/CustomReports/reportViews/{$report_view}");
         $div = $this->template->createElement('div', array('id' => "report_view_{$report_view}", 'class' => "dashboard_report"));
         $reportListNode->appendChild($div);
         $page = new I2CE_Page_ShowReport(array(), array($report_view), array('no_controls' => 1, 'flash_height' => $view_settings['height'], 'flash_width' => $view_settings['width'], 'results_id' => $report_view, 'height' => $view_settings['height'], 'width' => $view_settings['width'], 'label_size' => $view_settings['label_size']));
         $page->template = $this->template;
         $displayObj = $page->getDisplay($report_view);
         //$displays = $page->getDesiredDisplays( $report_view );
         //$displayObj = $page->instantiateDisplay( $displays[0], $report_view );
         $displayObj->display($div);
         $header = $this->template->getElementByName("report_view_display_name", 0, $div);
         if ($header instanceof DOMElement) {
             $link = $this->template->createElement('a', array("href" => "CustomReports/show/{$report_view}"), $header->nodeValue);
             $header->replaceChild($link, $header->firstChild);
         }
         //$url = "CustomReports/show/$report_view?no_controls=1&results_id=$report_view&flash_height=" . $view_settings['height'] . "&flash_width=" . $view_settings['width'] . "&height=" . $view_settings['height'] . "&width=" . $view_settings['width'];
         //$this->addAjaxLoad( "report_view_$report_view",$url,'report','CustomReports_PieChart,visualization_wrapper' );
     }
     return true;
 }
 /**
  * Perform any actions for the page
  * 
  * @returns boolean.  true on sucess
  */
 public function action()
 {
     $view = false;
     if (count($this->request_remainder) > 0) {
         $view = current($this->request_remainder);
     }
     $run_reports_in_bg = !array_key_exists('run_reports_in_background', $this->args) || $this->args['run_reports_in_background'];
     if ($run_reports_in_bg) {
         $use_reports = array();
         if ($view) {
             $use_reports = array($view);
         } else {
             $report_config = I2CE::getConfig()->traverse("/modules/CustomReports", true);
             $bkg_time = 0;
             $report_config->setIfIsSet($bkg_time, "times/background");
             foreach ($report_config->search_reports as $report => $report_info) {
                 // if background generation of reports is turned off, then don't run this unless
                 // overridden by the search report setting
                 // When the background process runs each report will check it's own staleness
                 // before running.
                 $force = $report_info->traverse("force");
                 if ((!is_numeric($bkg_time) || $bkg_time <= 0) && !$force) {
                     continue;
                 }
                 $use_reports[] = $report;
             }
         }
         $stale_reports = array();
         foreach ($use_reports as $report) {
             if (!I2CE_CustomReport::isStale($report)) {
                 continue;
             }
             $stale_reports[] = $report;
         }
         if (count($stale_reports) > 0) {
             $this->launchBackgroundPage("/CustomReports/generate/" . implode("/", $stale_reports));
         }
     }
     $this->template->setDisplayData("limit_description", false);
     if ($view) {
         return $this->actionSearch($view);
     } else {
         return $this->actionMenu();
     }
     //parent handles the show action
     return parent::action();
 }
    /**
     * Run the appropriate cron jobs based on the cron type.
     * @param string $type
     */
    public function cronjob($type)
    {
        // We need to run any normal hooks and not CLI hooks for this process if run from CLI
        $host_changed = false;
        if (!array_key_exists('HTTP_HOST', $_SERVER)) {
            $host_changed = true;
            $_SERVER['HTTP_HOST'] = '';
        }
        // Find all the Module Access modules that are available so the user can be set.
        $report_limits = I2CE_ModuleFactory::callHooks("get_report_module_limit_options");
        $limit_modules = array();
        foreach ($report_limits as $limit) {
            if (array_key_exists('module', $limit)) {
                $mod = I2CE_ModuleFactory::instance()->getClass($limit['module']);
                $limit_modules[] = array('module' => $mod, 'user' => $mod->getUser());
            }
        }
        $cron_type_where = array('operator' => "FIELD_LIMIT", 'style' => 'equals', 'field' => 'cron_type', 'data' => array('value' => $type));
        $reports = I2CE_FormStorage::listFields('cron_report', array('parent', 'report_view'), false, $cron_type_where);
        foreach ($reports as $report) {
            $view = $report['report_view'];
            $user = I2CE_FormFactory::instance()->createContainer($report['parent']);
            // Set the user on all access modules to limit results.
            foreach ($limit_modules as $module) {
                $module['module']->setUser($user->user);
            }
            $_SESSION['user_name'] = $user->username;
            $page = new I2CE_Page_ShowReport(array(), array($view));
            $template = $page->getTemplate();
            $display = $page->getDesiredDisplays($view);
            $use_display = 'Default';
            if ($display[0] != 'PieChart') {
                $use_display = $display[0];
            }
            $displayObj = $page->instantiateDisplay($use_display, $view);
            $config = I2CE::getConfig()->modules->CustomReports->reportViews->{$view};
            $template->loadRootText("<span id='siteContent' />");
            $contentNode = $template->getElementById('siteContent');
            $attachments = array();
            $report_name = $config->display_name;
            $report_desc = $config->description;
            $report_limit = '';
            $generated = strftime('%c');
            switch ($use_display) {
                case "CrossTab":
                    if ($displayObj->isExport()) {
                        $export = $displayObj->generateExport($contentNode, false);
                        $html = false;
                        $attachments[] = array('type' => "text/csv; charset=UTF-8", 'data' => $export, 'name' => $this->getFileName($report_name) . ".csv");
                        break;
                    }
                    // If not export then fall through to the Default
                // If not export then fall through to the Default
                case "Default":
                    $displayObj->unsetPaging();
                    $displayObj->display($contentNode);
                    $report_limit = $displayObj->getReportLimitsDescription();
                    $css = I2CE::getFileSearch()->search('CSS', 'customReports_display_Default.css');
                    $report_css = file_get_contents($css);
                    $report_table = $template->getElementById('report_table');
                    $report_content = $template->doc->saveHTML($report_table);
                    $html = <<<EOF
<?xml version="1.0" encoding="utf-8"?>'
<!DOCTYPE html>
<html>
<head>
    <title>Automated Report: {$report_name}</title>
    <style type="text/css">
{$report_css}
    </style>
</head>
<body>
    <h1>{$report_name}</h1>
    <h2>{$report_desc}</h2>
    <h3>{$report_limit}</h3>
    <p>Generated on: {$generated}</p>
    {$report_content}
</body>
</html>
EOF;
                    break;
                case "PDF":
                    $pdf = $displayObj->getPDF($contentNode);
                    $pdf_data = $pdf->Output($report_name, 'S');
                    $html = false;
                    $attachments[] = array('type' => 'application/pdf', 'data' => $pdf_data, 'name' => $this->getFileName($report_name) . ".pdf");
                    break;
                case "Export":
                    $export = $displayObj->generateExport();
                    $html = false;
                    $attachments[] = array('type' => $displayObj->getContentType(true), 'data' => $export, 'name' => $displayObj->getFileName());
                    break;
                default:
                    I2CE::raiseError("Unknown display type used for report display for user cron reports.");
                    break;
            }
            $email = $user->email;
            // This is duplicated from the Default setting so it can be in the main mail message as well.
            // It isn't called earlier to avoid duplicate processing with the Default display.
            if (!$html && $report_limit == '') {
                $report_limit = $displayObj->getReportLimitsDescription();
            }
            $mail_msg = wordwrap("This is the automated report for {$report_name}:  {$report_desc}.\nLimits are: {$report_limit}\nGenerated on: {$generated}.");
            if (I2CE_Mailer::mail($email, array('Subject' => 'Automated Report: ' . $report_name), $mail_msg, $html, $attachments)) {
                echo "Report mail {$report_name} (" . $report['report_view'] . ") sent to {$email}.\n";
            } else {
                echo "Report mail {$report_name} (" . $report['report_view'] . ") failed to {$email}.\n";
            }
            //$page->actionCommandLine( array(), array() );
        }
        if ($host_changed) {
            unset($_SERVER['HTTP_HOST']);
        }
        unset($_SESSION['user_name']);
        foreach ($limit_modules as $module) {
            $module['module']->setUser($module['user']);
        }
    }