protected function _display($supress_output = false)
 {
     $this->template->addHeaderLink('mootools-core.js');
     $this->template->addHeaderLink('mootools-more.js');
     parent::_display($supress_output);
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Errors:\n" . $errors);
     }
     $this->ff = I2CE_FormFactory::instance();
     if (!$this->request_exists('id') || !($formid = $this->request('id'))) {
         $this->pushError("Bad list id {$id}");
         //needs to be localized
         return false;
     }
     $success = true;
     list($form, $id) = array_pad(explode("|", $formid, 2), 2, '');
     I2CE::raiseError(print_r($this->request(), true));
     if ($id == '*') {
         $where = array('operator' => 'FIELD_LIMIT', 'field' => 'remap', 'style' => 'not_null', 'data' => array());
         $ids = I2CE_FormStorage::search($form, false, $where);
         I2CE::raiseError("Form {$form} has remapping data for " . implode(" ", $ids));
         if (count($ids) > 0) {
             foreach (I2CE_List::getFieldsMappingToList($form) as $rform => $fields) {
                 foreach ($fields as $fieldObj) {
                     $field = $fieldObj->getName();
                     foreach ($ids as $id) {
                         I2CE::raiseError("Checking for remaps on {$rform}+{$field}");
                         $success &= $this->doRemap($rform, $field, $form . '|' . $id);
                     }
                 }
             }
         }
         $url = "index.php/auto_list?form=" . $form;
     } else {
         $form = '';
         if (!$this->request_exists('form') || !($form = $this->request('form')) || !in_array($form, $this->ff->getForms())) {
             $this->pushError("Form {$form} not found");
             return false;
         }
         $field = '';
         if (!$this->request_exists('field') || !($field = $this->request('field'))) {
             $this->pushError("Bad Field {$field}");
             return false;
         }
         $success = $this->doRemap($form, $field, $formid);
         $url = "index.php/auto_list?id={$formid}&form=" . $form;
     }
     if ($success) {
         $this->pushContent("Data was succesully remapped.  Continue on to database lists <a href='{$url}'>site</a>?");
     } else {
         $this->pushContent("Data was <b>not</b> succesully remapped.  Continue on to database lists <a href='{$url}'>site</a>?");
     }
     return true;
 }
 /**
  *Abstract method to retreive/display the contents of the rendered forms
  * @param boolean $as_string.  Defaults to false 
  * @returns mixed.  If {$as_string} is false the it is a  boolean true on sucess.  If $as_string is true, then it is a string on success, false on failure
  */
 public function display($as_string = false)
 {
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Got errors:\n{$errors}");
     }
     $title = addslashes(str_replace(array(' ', "\n", "\t"), array('_', ' ', '_'), $this->std_form) . '.pdf');
     if (!$as_string) {
         $this->pdf->Output($title, 'D');
         exit;
         // we want to make sure there is no further output or that the $this->page->display() method is not called
     } else {
         return $this->pdf->Output($title, 'S');
     }
 }
 protected function _display($supress_output = false)
 {
     if (!$this->isPost()) {
         //not doing a data import
         return parent::_display($supress_output);
     } else {
         parent::_display($supress_output);
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Errors:\n" . $errors);
         }
         if (!$this->hasPermission('task(form_relationship_can_import)')) {
             $this->pushError("You do not have permission to import");
             return false;
         }
         $ignore_ids = $this->request_exists('ignore_ids') && $this->request('ignore_ids');
         $src = $_FILES['upload']['tmp_name'];
         $this->import($src, $ignore_ids);
         return true;
     }
 }
 protected function action_get($action)
 {
     switch ($action) {
         case 'publish':
             $params = $this->loadRequestParameters(self::$retrieve_single);
             try {
                 $svs = new iHRIS_SVS($params['id']);
             } catch (Exception $e) {
                 I2CE::raiseError("Couldn't create SVS for {$params['id']}");
                 return false;
             }
             if (!$svs->publishConceptList($params['version'], $params['lang'])) {
                 I2CE::raiseError("Couldn't publish SVS for {$params['id']}");
                 $this->userMessage("Could not publish Shared Value Set " . $params['id']);
             } else {
                 $this->userMessage("Published Shared Value Set " . $params['id']);
             }
             $this->redirect($this->page . '/config');
             return true;
         case 'RetrieveMultipleValueSets':
             $params = $this->loadRequestParameters(self::$retrieve_multi);
             if (!($svs_doc = $this->generateMultiDoc($params)) instanceof DOMDocument) {
                 I2CE::raiseError("Could not retrieve multiples");
                 return false;
             }
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Got errors:\n{$errors}");
             }
             header('Content-Type: text/xml');
             echo $svs_doc->saveXML();
             exit(0);
         default:
         case 'RetrieveValueSet':
             $params = $this->loadRequestParameters(self::$retrieve_single);
             if (!is_string($svs = iHRIS_SVS::getPublishedConceptList($params['id'], $params['version'], $params['lang']))) {
                 I2CE::raiseError("Couldn't retrieve SVS for {$params['id']} on version {$params['version']} language {$params['lang']}");
                 return false;
             }
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Got errors:\n{$errors}");
             }
             header('Content-Type: text/xml');
             header('Content-Disposition: attachment; filename="' . $params['id'] . '.xml"');
             echo $svs;
             exit(0);
     }
 }
 protected function action()
 {
     parent::action();
     if (!$this->config instanceof I2CE_MagicDataNode) {
         $this->reshow(true);
         //show the parent node.
         return;
     }
     $reshow = false;
     switch ($this->page()) {
         case 'upload':
             I2CE::raiseError("Upload on " . $this->config->getPath(false) . "\n" . print_r($_FILES, true));
             if (!array_key_exists('upload', $_FILES) || array_key_exists('error', $_FILES['upload']) && $_FILES['upload']['error'] > 0 || ($upload = file_get_contents($_FILES['upload']['tmp_name'])) === false) {
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if (strlen($upload) != $_FILES['upload']['size']) {
                 I2CE::raiseError("Upload size mismatch " . strlen($upload) . ' != ' . $_FILES['upload']['size']);
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if ($this->config->is_parent()) {
                 $this->userMessage("Cannot set value on parent node");
                 break;
             }
             $content = $this->config;
             if ($content->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($content->hasAttribute('binary') && $content->getAttribute('binary')) {
                 $upload = base64_encode($upload);
                 $content->setValue($upload);
                 $content->setAttribute('encoding', 'base64');
                 $content->setAttribute('binary', '1');
             } else {
                 $content->setValue($upload);
             }
             break;
         case 'upload_binary':
             I2CE::raiseError("Upload Binary on " . $this->config->getPath(false) . "\n" . print_r($_FILES, true));
             if (!array_key_exists('upload', $_FILES) || array_key_exists('error', $_FILES['upload']) && $_FILES['upload']['error'] > 0 || ($upload = file_get_contents($_FILES['upload']['tmp_name'])) === false) {
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if (strlen($upload) != $_FILES['upload']['size']) {
                 I2CE::raiseError("Upload size mismatch " . strlen($upload) . ' != ' . $_FILES['upload']['size']);
                 $this->userMessage("Could not upload " . $_FILES['upload']['name']);
                 break;
             }
             if ($this->config->is_scalar()) {
                 $this->userMessage("Cannot set value on parent node");
                 break;
             }
             $content = $this->config->traverse('content', true, false);
             $name = $this->config->traverse('name', true, false);
             $type = $this->config->traverse('type', true, false);
             if ($content->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($name->is_parent()) {
                 $this->userMessage("Cannot overwrite content node");
                 break;
             }
             if ($type->is_parent()) {
                 $this->userMessage("Cannot overwrite type node");
                 break;
             }
             //I2CE::raiseError("Setting " . $this->config->getPath() );
             $upload = base64_encode($upload);
             $content->setValue($upload);
             $name->setValue($_FILES['upload']['name']);
             $type->setValue($_FILES['upload']['type']);
             $content->setAttribute('binary', 1);
             $content->setAttribute('encoding', 'base64');
             break;
         case 'load':
             I2CE::raiseError("Begin load:" . print_r($this->request(), true));
             $transform = false;
             if (($transform_key = $this->request('transform_key')) && I2CE_MagicDataNode::checkKey($transform_key) && I2CE::getConfig()->setIfIsSet($transform, "/modules/magicDataBrowser/transforms/" . $this->request('transform_key')) && $transform) {
                 if (substr($transform, 0, 7) == 'file://' && (!($transform_file = I2CE::getFileSearch()->search('XSL', $file_name = substr($transform, 7))) || !($transform = file_get_contents($transform_file)))) {
                     I2CE::raiseError("Could not load {$file_name} for transform");
                     $this->userMessage("Invalid registered transform");
                     return false;
                 }
             } else {
                 if (array_key_exists('transform', $_FILES) && !(array_key_exists('error', $_FILES['transform']) && $_FILES['transform']['error'] > 0)) {
                     $transform = file_get_contents($_FILES['transform']['tmp_name']);
                 }
             }
             I2CE::raiseError("Loading with transform:{$transform}");
             if ($this->actionLoad($transform)) {
                 $this->userMessage("Data successuly loaded");
             } else {
                 $this->userMessage("There was a problem loading the data");
             }
             break;
         case 'erase':
             $name = $this->config->getName();
             $parent = $this->config->traverse('../');
             if ($this->isPost() && $this->config->getPath() != $this->config->traverse('/')->getPath()) {
                 //don't allow an erase of the top level node
                 unset($parent->{$name});
             }
             $reshow = true;
             break;
         case 'parent':
             if ($this->isPost() && $this->config->is_indeterminate()) {
                 $this->config->set_parent();
             }
             break;
         case 'scalar':
             if ($this->isPost() && $this->config->is_indeterminate()) {
                 $this->config->set_scalar();
             }
             break;
         case 'add':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key)) {
                     $this->config->traverse($key, true, false);
                 }
             }
             break;
         case 'add_parent':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key) && ($newNode = $this->config->traverse($key, true, false)) instanceof I2CE_MagicDataNode) {
                     $newNode->set_parent();
                 }
             }
             break;
         case 'add_scalar':
             if ($this->post_exists('browser_magic_data_add_key')) {
                 $key = $this->post('browser_magic_data_add_key');
                 if (I2CE_MagicDataNode::checkKey($key) && !$this->config->pathExists($key) && ($newNode = $this->config->traverse($key, true, false)) instanceof I2CE_MagicDataNode) {
                     $newNode->set_scalar();
                 }
             }
             break;
         case 'set':
             I2CE::raiseError("Try to set:0");
             if ($this->post_exists('browser_magic_data_value') && $this->post_exists('browser_magic_data_key')) {
                 I2CE::raiseError("Try to set:1");
                 $key = $this->post('browser_magic_data_key');
                 $value = $this->post('browser_magic_data_value');
                 if ($this->config->offsetExists($key) && is_scalar($value)) {
                     I2CE::raiseError("Try to set:2");
                     if ($this->config->is_translatable($key)) {
                         $locales = I2CE_Locales::getPreferredLocales();
                         reset($locales);
                         $locale = current($locales);
                         $this->config->setTranslation($locale, $value, $key);
                         if ($locale == I2CE_Locales::DEFAULT_LOCALE) {
                             $this->config->__set($key, $value);
                         }
                     } else {
                         $this->config[$key] = $value;
                     }
                 }
             }
             //we redirect so a reload does not post and so that if the page's display depends on the value that is being
             //set, we redisplay it.
             break;
         case 'download':
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Errors:\n" . $errors);
             }
             $value = $this->config->getValue();
             header("Cache-Control: max-age=1, s-maxage=1, no-store, no-cache, must-revalidate");
             header('Cache-Control: post-check=0, pre-check=0', false);
             header('Pragma: no-cache');
             header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10) . " GMT");
             header("ETag: PUB" . time());
             header("Pragma: no-cache");
             header("Content-length: " . strlen($value));
             header('Content-Disposition: attachment; filename="' . $this->config->getName() . '"');
             $mime_type = I2CE_MimeTypes::magicMimeType($value);
             I2CE::raiseError($mime_type);
             header('Content-type:' . $mime_type);
             session_cache_limiter("nocache");
             echo $value;
             die;
         case 'trans':
             $this->config->setTranslatable(null, !$this->config->is_translatable());
             break;
         case 'show':
         case 'mini':
             $this->actionDisplayConfig();
             $reshow = null;
             break;
         default:
             break;
     }
     if ($reshow !== null) {
         $this->reshow($reshow);
     }
 }
    public function streamCache($ids = false, $last_modified = -1, $headers = false, $pre = '', $post = '', $wrap = true)
    {
        I2CE::longExecution(array("max_execution_time" => 1800));
        $results = $this->getCache($ids, $last_modified);
        if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
            I2CE::raiseError("Got errors:\n{$errors}");
        }
        if (array_key_exists('HTTP_HOST', $_SERVER)) {
            if (!is_array($headers)) {
                $headers = array('Content-Type: text/xml');
            }
            foreach ($headers as $header) {
                header($header);
            }
        }
        flush();
        if ($pre) {
            echo $pre;
            flush();
        }
        if ($wrap) {
            echo '
<csd:CSD xmlns:csd="urn:ihe:iti:csd:2013" >
';
        }
        foreach (array('organization', 'service', 'facility', 'provider') as $directory) {
            if ($wrap) {
                echo "<csd:" . $directory . "Directory>";
                flush();
            }
            if ($this->directory == $directory && $results) {
                while ($result = $results->fetchRow()) {
                    I2CE::longExecution(array("max_execution_time" => 1800));
                    $entity = $result->xml_entry;
                    echo $entity;
                    flush();
                }
            }
            if ($wrap) {
                echo "</csd:" . $directory . "Directory>\n";
                flush();
            }
        }
        flush();
        if ($wrap) {
            echo '</csd:CSD>
';
        }
        if ($post) {
            echo $post;
        }
        flush();
    }
    protected function action_full_soap($last_modified = -1, $cache_names = false, $headers = false, $content = false)
    {
        if (!$content) {
            $content = file_get_contents("php://input");
        }
        $content = file_get_contents("php://input");
        if (!$content || !($req_doc = new DOMDocument("1.0", "UTF-8")) || !$req_doc->loadXML($content) || !($xpath = new DOMXPath($req_doc)) || !$xpath->registerNamespace('soap', 'http://www.w3.org/2003/05/soap-envelope') || !$xpath->registerNamespace('wsa', 'http://www.w3.org/2005/08/addressing') || !$xpath->registerNamespace('csd', 'urn:ihe:iti:csd:2013') || !($results = $xpath->query('/soap:Envelope/soap:Body/csd:getModificationsRequest/csd:lastModified')) instanceof DOMNodeList || !($results->length == 1) || !($item = $results->item(0)) instanceof DOMElement || !($mod_time = $item->textContent) || !($results = $xpath->query('/soap:Envelope/soap:Header/wsa:MessageID')) instanceof DOMNodeList || !($results->length == 1) || !($item = $results->item(0)) instanceof DOMElement || !($msg_id = $item->textContent)) {
            I2CE::raiseError("Invalid request");
            //NEED TO ADD IN ERROR HANDLING ACCORDING TO SPEC
            return false;
        }
        if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
            I2CE::raiseError("Got errors:\n{$errors}");
        }
        if (!is_array($headers)) {
            $headers = array('Content-Type: text/xml');
        }
        foreach ($headers as $header) {
            header($header);
        }
        echo '<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:csd="urn:ihe:iti:csd:2013"> <soap:Header>
            <wsa:Action soap:mustUnderstand="1" >urn:ihe:iti:csd:2013:GetDirectoryModificationsResponse</wsa:Action>
            <wsa:MessageID>urn:uuid:' . iHRIS_UUID_Map::generateUUID() . '</wsa:MessageID>
            <wsa:To soap:mustUnderstand="1"> http://www.w3.org/2005/08/addressing/anonymous</wsa:To> <wsa:RelatesTo>' . $msg_id . '</wsa:RelatesTo>
            </soap:Header>
            <soap:Body>
            <csd:getModificationsResponse>
';
        flush();
        $this->action_full_stream($mod_time, false, array(), false, false);
        echo '</csd:getModificationsResponse>
    </soap:Body>
</soap:Envelope>';
    }
 protected function outputTemplate($odf, $basename)
 {
     $odt_temp_file = tempnam(sys_get_temp_dir(), '_ODT_');
     $odf->saveToDisk($odt_temp_file);
     $unoconv = false;
     if (I2CE::getConfig()->setIfIsSet($unoconv, "/modules/PrintedFormsODT/unoconv/exec")) {
         $unoconv = system("which " . $unoconv);
     }
     $conversions = array();
     I2CE::getConfig()->setIfIsSet($conversions, "/modules/PrintedFormsODT/unoconv/conversions", true);
     $format = false;
     if (array_key_exists('format', $this->args)) {
         $format = $this->args['format'];
     }
     if ($this->request_exists('format')) {
         $format = $this->request('format');
     }
     $command_options = '';
     if ($unoconv && is_string($format) && is_array($conversions) && array_key_exists($format, $conversions) && is_array($conversion = $conversions[$format]) && array_key_exists('mime', $conversion) && is_string($mime = $conversion['mime']) && array_key_exists('ext', $conversion) && is_string($ext = $conversion['ext'])) {
         $conv_temp_file = tempnam(sys_get_temp_dir(), '_' . $format . '_');
         $export_options = '';
         if (array_key_exists('export_options', $this->args) && is_array($this->args['export_options']) && array_key_exists($format, $this->args['export_options']) && is_string($t_export_options = $this->args['export_options'][$format]) && strlen($t_export_options = trim($t_export_options)) > 0) {
             $export_options = ' -e ' . $t_export_options . ' ';
         }
         $exec = $unoconv . ' -o ' . $conv_temp_file . $export_options . ' -f ' . $format . ' ' . $odt_temp_file;
         //NEED TO DO ON UBUNTU SERVER: sudo mkdir /home/www-data; sudo  chown www-data:www-data /home/www-data
         $error = 0;
         system($exec, $error);
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Errors:\n" . $errors);
         }
         I2CE::raiseError("Converting with {$exec}");
         if ($error == 0) {
             header('Content-type: ' . $mime);
             header('Content-Disposition: attachment; filename="' . $basename . '.' . $ext . '"');
             readfile($conv_temp_file);
             exit;
         }
         I2CE::raiseError("Error ({$error}) with {$exec}");
     }
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Errors:\n" . $errors);
     }
     header('Content-type: application/vnd.oasis.opendocument.text');
     header('Content-Disposition: attachment; filename="' . $basename . '.odt"');
     readfile($odt_temp_file);
     exit;
 }
 protected function action()
 {
     switch ($this->getAction()) {
         case 'xml':
             header("Content-type: text/xml");
             $children = $this->request_exists('children') && $this->request('children');
             if (!($obj = $this->getPrimary()) instanceof I2CE_Form) {
                 I2CE::raiseError("Bad Object");
                 return false;
             }
             $out = $obj->getXMLRepresentation(false, null, false, $children);
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Got errors:\n{$errors}");
             }
             header("Content-disposition: attachment; filename=\"" . $obj->getName() . "_" . $obj->getID() . ".xml");
             echo $out;
             exit(0);
         case 'json':
             header("Content-type: application/json");
             $children = $this->request_exists('children') && $this->request('children');
             if (!($obj = $this->getPrimary()) instanceof I2CE_Form) {
                 I2CE::raiseError("Bad Object");
                 return false;
             }
             $out = json_encode(simplexml_load_string($obj->getXMLRepresentation(false, null, false, $children)));
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Got errors:\n{$errors}");
             }
             echo $out;
             exit(0);
         case 'json_small':
             header("Content-type: application/json");
             if (!($obj = $this->getPrimary()) instanceof I2CE_Form) {
                 I2CE::raiseError("Bad Object");
                 return false;
             }
             if ($this->isPost()) {
                 $vals = json_decode($in = file_get_contents('php://input'), true);
                 $out = "{'success':0}";
                 if (is_array($vals)) {
                     if (array_key_exists('id', $vals)) {
                         $obj->setID($vals['id']);
                         $obj->populate();
                     }
                     $ok_fields = $obj->getFieldNames();
                     $ok_fields[] = 'parent';
                     foreach ($vals as $field => $data) {
                         if (!is_string($data) || !in_array($field, $ok_fields) || !($fieldObj = $obj->getField($field)) instanceof I2CE_FormField) {
                             continue;
                         }
                         $fieldObj->setFromDB($data);
                     }
                     I2CE::raiseError("JSON Save:" . $obj->getNameID());
                     $obj->save($this->user);
                     $out = "{'success':1}";
                 }
             } else {
                 $vals = array();
                 $fields = $obj->getFieldNames();
                 $fields = array_merge($fields, array('id', 'parent', 'created', 'last_modified'));
                 foreach ($fields as $field) {
                     if (!($fieldObj = $obj->getField($field)) instanceof I2CE_FormFIeld) {
                         continue;
                     }
                     $vals[$field] = $fieldObj->getDBValue();
                 }
                 $out = json_encode($vals);
             }
             if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
                 I2CE::raiseError("Got errors:\n{$errors}");
             }
             echo $out;
             exit(0);
         default:
             return parent::action();
     }
 }
 /**
  *Abstract method to retreive/display the contents of the rendered forms
  * @param boolean $as_string.  Defaults to false 
  * @returns mixed.  If {$as_string} is false the it is a  boolean true on sucess.  If $as_string is true, then it is a string on success, false on failure
  */
 public function display($as_string = false)
 {
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Got errors:\n{$errors}");
     }
     if ($as_string) {
         //we don't want mime type.  this goes to the archive
         $this->odf->saveToDisk();
         //
         return file_get_contents($this->odf->getTmpFile());
     } else {
         //we do want mime type.  this goes to the browser
         $this->odf->exportAsAttachedFile(addslashes($this->getFileName()));
         exit;
         // we want to make sure there is no further output or that the $this->page->display() method is not called
     }
 }
 /**
  * Display the report
  * @param DOMNode $contentNode The DOM node we wish to display into
  * @param boolean $processResults Defaults to true meaning we run through the results
  * @param mixed $controls.  If null (default), we display all the report controsl.  If string or an array of string, we only display the indicated controls
  * @return mixed I2CE_PDF on success, boolean otherwise
  */
 public function getPDF($contentNode, $processResults = true, $controls = null)
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     $this->resultsTable = array();
     if ($this->defaultOptions['table']['has_header']) {
         $formfields = $this->getDisplayFieldsData();
         $headers = array('#');
         foreach ($formfields as $formfield => $data) {
             if (!$data) {
                 continue;
             }
             $headers[$formfield] = $data['header'];
         }
         $this->resultsTable[] = $headers;
     }
     $data = $this->getResults();
     if (!$this->processResults($data, $contentNode)) {
         I2CE::raiseError("Could not get results");
         return false;
     }
     $encoding = new I2CE_Encoding('ASCII');
     //make sure we have somethin in our options
     $pdf = new I2CE_PDF($encoding, $this->defaultOptions['paper_orientation'], $this->defaultOptions['unit_of_measure'], $this->defaultOptions['paper_size']);
     //portrait, we are doing measurements in inches, letter paper
     //setup the main page display style
     $this->addFont($this->defaultOptions['main']['font'], $pdf);
     $pdf->SetTopMargin($this->defaultOptions['main']['top_margin']);
     $pdf->SetCompression($this->defaultOptions['compression']);
     $pdf->SetLineSpacing($this->defaultOptions['line_spacing']);
     //setup the header
     $pdf->setPrintHeader($this->defaultOptions['header']['show']);
     $pdf->setPrintFooter(false);
     $this->addFont($this->defaultOptions['header']['font'], $pdf);
     $pdf->setHeaderFont($this->defaultOptions['header']['font']['name'], $this->defaultOptions['header']['font']['style'], $this->defaultOptions['header']['font']['size']);
     $title = '';
     if ($this->defaultOptions['header']['title_prefix']) {
         $title = $this->defaultOptions['header']['title_prefix'] . ': ';
     }
     $title .= $this->config->display_name;
     $text = '';
     if ($this->defaultOptions['header']['text_prefix']) {
         if ($this->config->description) {
             $text = $this->defaultOptions['header']['text_prefix'] . ': ' . $this->config->description;
         } else {
             $text = $this->defaultOptions['header']['text_prefix'];
         }
     } else {
         if ($this->config->description) {
             $text = $this->config->description;
         } else {
             $text = '';
         }
     }
     $user = new I2CE_User();
     $name = $user->firstname . ' ' . $user->lastname;
     $time = strftime("%c");
     $desc = "This report was printed by {$name} on {$time}.\n";
     $limitsDesc = $this->getReportLimitsDescription();
     if (strlen($limitsDesc) > 0) {
         $desc .= "Report Limited by: " . $limitsDesc . "\n";
     }
     $pdf->setHeaderData($this->defaultOptions['header']['logo']['file'], $this->defaultOptions['header']['logo']['width'], $title, $text, $desc);
     $pdf->setHeaderMargin($this->defaultOptions['header']['margin']);
     // load our hyphenation dictionary
     $hyphen = new I2CE_Hyphen($encoding);
     $hyphen->LoadHyphenDictionary($this->defaultOptions['hyphenation_file']);
     $pdf->SetHyphenationDictionary($hyphen);
     //setup table style
     $pdf->SetTableHeaderFillColor($this->defaultOptions['table']['header']['fill_color']);
     $pdf->SetTableHeaderTextColor($this->defaultOptions['table']['header']['text_color']);
     $pdf->SetTableDataFillColor($this->defaultOptions['table']['data']['fill_color']);
     $pdf->SetTableDataTextColor($this->defaultOptions['table']['data']['text_color']);
     $pdf->SetMinTableCellWidth($this->defaultOptions['table']['min_cell_width']);
     $pdf->SetTableFramingColor($this->defaultOptions['table']['framing_color']);
     $pdf->SetTableColSpacing($this->defaultOptions['table']['column_spacing']);
     if (strtolower($this->defaultOptions['table']['width_style']) == 'explicit') {
         if (!empty($this->defaultOptions['table']['explicit_widths'])) {
             $pdf->SetTableWidths($this->defaultOptions['table']['explicit_widths']);
         } else {
             //fall back to a safe option
             $pdf->SetAutoTableWidthStyle('ALL');
         }
     } else {
         $pdf->SetAutoTableWidthStyle($this->defaultOptions['table']['width_style']);
     }
     //get on with displaying the report
     $this->setFont($this->defaultOptions['main']['font'], $pdf);
     $pdf->AddPage();
     if ($this->defaultOptions['table']['has_header']) {
         if ($this->defaultOptions['table']['use_running_header']) {
             $table_header_options = 2;
         } else {
             $table_header_options = 1;
         }
     } else {
         $table_header_options = 0;
     }
     $pdf->MakeTable($this->resultsTable, $this->defaultOptions['table']['border'], $this->defaultOptions['table']['max_width'], $this->defaultOptions['table']['data']['justification'], $table_header_options, $this->defaultOptions['table']['header']['justification'], 1);
     $pdf->Close();
     $title = addslashes(str_replace(array(' ', "\n", "\t"), array('_', ' ', '_'), $this->config->display_name) . '.pdf');
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Errors:\n" . print_r($errors, true));
     }
     return $pdf;
 }
 protected function dump($vars)
 {
     $file_name = $vars['name'];
     if (empty($file_name)) {
         //do nothing if name is not set
         I2CE::raiseError("No file specified", E_USER_NOTICE);
         return;
     }
     //get the extension
     if (array_key_exists('ext', $vars)) {
         $ext = strtolower($vars['ext']);
     } else {
         $ext = strtolower(substr(strrchr($file_name, "."), 1));
     }
     $category = null;
     if (array_key_exists('cat', $vars)) {
         $category = $vars['cat'];
     }
     if (empty($category)) {
         //try to see if we have a default category
         if (array_key_exists($ext, $this->default_categories)) {
             $category = $this->default_categories[$ext];
         }
         if (empty($category)) {
             //do nothing if no category found
             I2CE::raiseError("No file category specified for ({$file_name}). Valid categories are:" . print_r($this->default_categories, true), E_USER_NOTICE);
             I2CE::raiseError(print_r($this->default_categories, true));
             return;
         }
     }
     if (!in_array($category, $this->allowedCategories)) {
         //we are not allowed to search this category
         I2CE::raiseError("Not allowed to search category ({$category}).  Allowed are:\n" . print_r($this->allowedCategories, true), E_USER_NOTICE);
         return;
     }
     $file_loc = I2CE::getFileSearch()->search($category, $file_name);
     $locale = I2CE::getFileSearch()->getLocaleOfLastSearch();
     if (!$file_loc) {
         //do nothing if we can't find the file
         I2CE::raiseError("Cannot find ({$file_name}). Search category is {$category} , Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath($category), true), E_USER_NOTICE);
         return;
     }
     if (!array_key_exists('apdContent', $vars)) {
         $vars['apdContent'] = null;
     }
     if (!array_key_exists('content', $vars)) {
         $vars['content'] = null;
     }
     //$headers = $this->doHeader($file_name,$file_loc,$ext,$vars['content'],$vars['apdContent']);
     $headers = $this->doHeader($file_name, $ext, $vars['content'], $vars['apdContent']);
     $config = I2CE::getConfig();
     $cacheTime = 600;
     // defaults to 10 minutes
     if (isset($config->modules->FileDump->cache_time)) {
         $cacheTime = $config->modules->FileDump->cache_time * 60;
     }
     $ttl = 3600;
     // defaults to one hour
     if ($config->is_scalar("/modules/FileDump/ttl")) {
         $ttl = $config->modules->FileDump->ttl * 60;
     }
     if (I2CE_Dumper::dumpContents($file_loc, $headers, $cacheTime)) {
         I2CE_Dumper::cacheFileLocation(MDB2::singleton()->database_name, $file_name, $locale, $headers, $file_loc, $cacheTime, $ttl);
     }
 }
 /**
  * Handles GET requests for a binary field
  * The relevant get variables are:
  *<ul><li> cat -- the I2CE_FileSearch category we should be looking for</li>
  *    <li> name -- the filename we are looking for</li>
  *</ul>
  *As an alternative (mainly b/c libxml's xmlSetProp (which is used by PHP's DOM) which
  * will automatically escape &)  you can set the variable encoded=ENC_BLAH   where ENC_BLAH is
  * an urlencoded string  with the cat and name variables set e.g urlencode("cat=SCRIPTS&name=somescript.js")
  */
 public function display($supress_output = false)
 {
     if ($_SERVER['REQUEST_METHOD'] != "GET" && $_SERVER['REQUEST_METHOD'] != "HEAD" || !$this->request_exists('formid') || !$this->request_exists('field')) {
         //do nothing if it is not a GET request
         exit;
     }
     $field = $this->request('field');
     $formid = $this->request('formid');
     if ($this->request_exists('tmp_key')) {
         if (!($formObj = I2CE_FormFactory::instance()->createContainer($formid)) instanceof I2CE_Form) {
             exit;
         }
         if (!$field || !($fieldObj = $formObj->getField($field)) instanceof I2CE_FormField_BINARY_FILE) {
             exit;
         }
         $fieldObj->setTempKey($this->request('tmp_key'));
         $fieldObj->setFromTemporaryTable();
     } else {
         if (!$this->request_exists('formid')) {
             exit;
         }
         if (!($formObj = I2CE_FormFactory::instance()->createContainer($formid)) instanceof I2CE_Form) {
             exit;
         }
         if (!$field || !($fieldObj = $formObj->getField($field)) instanceof I2CE_FormField_BINARY_FILE) {
             exit;
         }
         $formObj->populate();
     }
     //we are good to go  dump and die.
     $cacheTime = 60;
     // defaults to 1 minute
     if (I2CE::getConfig()->setIfIsSet($cacheTime, '/modules/BinFields/cache_time')) {
         $caheTime = $cacheTime * 60;
     }
     I2CE_Dumper::prepForDump($fieldObj->getModTime(), $fieldObj->getContentLength(), $fieldObj->getHeaders(), $cacheTime);
     echo $fieldObj->getValue();
     exit;
 }
 protected function outputTemplate($odf, $basename)
 {
     if (!array_key_exists('tmp_dir', $this->args) || !is_scalar($tmp_dir = $this->args['tmp_dir']) || !is_dir($tmp_dir)) {
         $tmp_dir = sys_get_temp_dir();
     }
     $odt_temp_file = tempnam($tmp_dir, '_ODT_');
     $odf->saveToDisk($odt_temp_file);
     $unoconv = false;
     if (I2CE::getConfig()->setIfIsSet($unoconv, "/modules/PrintedFormsODT/unoconv/exec")) {
         $unoconv = system("which " . $unoconv);
     }
     $conversions = array();
     I2CE::getConfig()->setIfIsSet($conversions, "/modules/PrintedFormsODT/unoconv/conversions", true);
     $format = false;
     if (array_key_exists('format', $this->args)) {
         $format = $this->args['format'];
     }
     if ($this->request_exists('format')) {
         $format = $this->request('format');
     }
     $command_options = '';
     if ($unoconv && is_string($format) && is_array($conversions) && array_key_exists($format, $conversions) && is_array($conversion = $conversions[$format]) && array_key_exists('mime', $conversion) && is_string($mime = $conversion['mime']) && array_key_exists('ext', $conversion) && is_string($ext = $conversion['ext'])) {
         $conv_temp_file = tempnam($tmp_dir, '_' . $format . '_');
         $export_options = '';
         if (array_key_exists('export_options', $this->args) && is_array($this->args['export_options']) && array_key_exists($format, $this->args['export_options']) && is_string($t_export_options = $this->args['export_options'][$format]) && strlen($t_export_options = trim($t_export_options)) > 0) {
             $export_options = ' -e ' . $t_export_options . ' ';
         }
         $connection = '';
         if (array_key_exists('connection', $this->args) && is_string($t_connection = $this->args['connection']) && strlen($t_connection = trim($t_connection)) > 0) {
             $connection = ' -c ' . $t_connection . ' ';
         }
         //On Ubuntu server 12.04 the odt needs chmod 605 before of try to use unoconv
         chmod($odt_temp_file, 0605);
         $multiple = false;
         $unoconv_config = I2CE::getConfig()->modules->PrintedFormsODT->unoconv;
         $unoconv_config->setIfIsSet($multiple, "allow_multiple");
         $home_idx = 1;
         if ($multiple) {
             while ($home_idx) {
                 if ($unoconv_config->is_parent("status/{$home_idx}")) {
                     $avail = 0;
                     $unoconv_config->setIfIsSet($avail, "status/{$home_idx}/available");
                     if ($avail) {
                         break;
                     } else {
                         $home_idx++;
                         continue;
                     }
                 }
                 break;
             }
             $unoconv_config->status->{$home_idx}->available = 0;
             if (!file_exists("/tmp/unoconv_homes/home{$home_idx}")) {
                 mkdir("/tmp/unoconv_homes/home{$home_idx}", 0755, true);
             }
             $exec = "HOME=/tmp/unoconv_homes/home{$home_idx} {$unoconv} --port=400{$home_idx} -o {$conv_temp_file} {$export_options} -f {$format} {$odt_temp_file}";
         } else {
             $exec = $unoconv . ' -o ' . $conv_temp_file . $export_options . ' -f ' . $format . ' ' . $odt_temp_file;
         }
         //NEED TO DO ON UBUNTU SERVER: sudo mkdir /home/www-data; sudo  chown www-data:www-data /home/www-data
         $error = 0;
         system($exec, $error);
         if ($multiple) {
             $unoconv_config->status->{$home_idx}->available = 1;
         }
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Errors:\n" . $errors);
         }
         I2CE::raiseError("Converting with {$exec}");
         if ($error == 0) {
             header('Content-type: ' . $mime);
             header('Content-Disposition: attachment; filename="' . $basename . '.' . $ext . '"');
             readfile($conv_temp_file);
             exit;
         }
         I2CE::raiseError("Error ({$error}) with {$exec}");
     }
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Errors:\n" . $errors);
     }
     header('Content-type: application/vnd.oasis.opendocument.text');
     header('Content-Disposition: attachment; filename="' . $basename . '.odt"');
     readfile($odt_temp_file);
     exit;
 }
 /**
  * Display the report
  * @param DOMNode $contentNode The DOM node we wish to display into
  * @param boolean $processResults Defaults to true meaning we run through the results
  * @param mixed $controls.  If null (default), we display all the report controsl.  If string or an array of string, we only display the indicated controls
  * @returns boolean. true on sucess
  */
 public function display($contentNode, $processResults = true, $controls = null)
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     $this->saveDefaultView();
     $template = $this->defaultOptions['odt_template'];
     $template_upload = false;
     $template_file = null;
     if ($this->config->setIfIsSet($template_upload, "printed_forms/{$template}/template_upload", true) && array_key_exists('content', $template_upload) && $template_upload['content'] && array_key_exists('name', $template_upload) && $template_upload['name']) {
         $template_file = $template_upload['name'];
         $pos = strrpos($template_file, '.');
         if ($pos !== false) {
             $name = substr($template_file, 0, $pos);
         } else {
             $name = $template_file;
         }
         $template_loc = tempnam(sys_get_temp_dir(), basename($name . '_')) . '.odt';
         file_put_contents($template_loc, $template_upload['content']);
     } else {
         $this->config->setIfIsSet($template_file, "printed_forms/{$template}/template");
         $template_loc = I2CE::getFileSearch()->search('ODT_TEMPLATES', $template_file);
         if (!$template_loc) {
             I2CE::raiseError("No template file found from {$template_file}");
             return false;
         }
     }
     $this->header_vars = array();
     foreach ($this->getDisplayFieldsData() as $formfield => $data) {
         $this->header_vars["++header+{$formfield}"] = $data['header'];
         list($formObj, $fieldObj) = $this->getFormFieldObjects($formfield);
         $this->image_objs[$formfield] = $fieldObj instanceof I2CE_FormField_IMAGE;
         $this->extra[$formfield] = array();
     }
     $this->limit_vars = $this->getLimitVars();
     $odf_config = array('DELIMITER_LEFT' => '{{{', 'DELIMITER_RIGHT' => '}}}', 'ZIP_PROXY' => 'PhpZipProxy');
     $this->odf = new I2CE_Odf($template_loc, $odf_config);
     try {
         $this->odf->setVars('++report_title', $this->config->display_name, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setStyleVars('++report_title', $this->config->display_name, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setVars('++report_description', $this->config->description, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setStyleVars('++report_description', $this->config->description, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     foreach ($this->header_vars as $key => $val) {
         try {
             $this->odf->setVars($key, $val, $this->encoding, $this->charset);
         } catch (OdfException $e) {
             //It's ok if it's not there so don't do anything.
         }
         try {
             $this->odf->setStyleVars($key, $val, $this->encoding, $this->charset);
         } catch (OdfException $e) {
             //It's ok if it's not there so don't do anything.
         }
     }
     foreach ($this->limit_vars as $key => $val) {
         try {
             $this->odf->setVars($key, $val, $this->encoding, $this->charset);
         } catch (OdfException $e) {
             //It's ok if it's not there so don't do anything.
         }
         try {
             $this->odf->setStyleVars($key, $val, $this->encoding, $this->charset);
         } catch (OdfException $e) {
             //It's ok if it's not there so don't do anything.
         }
     }
     $user = new I2CE_User();
     $name = $user->firstname . ' ' . $user->lastname;
     try {
         $this->odf->setVars('++user_name', $name, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setStyleVars('++user_name', $name, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     $time = strftime("%c");
     try {
         $this->odf->setVars('++time', $time, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setStyleVars('++time', $time, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     $limitsDesc = $this->getReportLimitsDescription();
     try {
         $this->odf->setVars('++report_limit', $limitsDesc, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf->setStyleVars('++report_limit', $limitsDesc, $this->encoding, $this->charset);
     } catch (OdfException $e) {
         //It's ok if it's not there so don't do anything.
     }
     try {
         $this->odf_row = $this->odf->setSegment('report_row');
     } catch (OdfException $e) {
         I2CE::raiseError("Couldn't find report_row in ODT template {$template_loc}.");
         return false;
     }
     $keys = $this->odf_row->getKeys();
     foreach ($this->odf_row->getKeys() as $key) {
         if (!is_string($key) || strlen($key) < 1) {
             continue;
         }
         if ($key[0] == '+') {
             continue;
         }
         list($namedform, $field, $t_extra) = array_pad(explode("+", $key, 3), 3, '');
         $extra = array();
         if (is_string($t_extra) && strlen($t_extra) > 0) {
             $t_extra = explode(',', $t_extra);
             foreach ($t_extra as $ex) {
                 list($ex_k, $ex_v) = array_pad(explode('=', $ex, 2), 2, '');
                 if (!$ex_k || !$ex_v) {
                     continue;
                 }
                 $extra[$ex_k] = $ex_v;
             }
         }
         $namedform = trim($namedform);
         $field = trim($field);
         $this->extra[$namedform . '+' . $field] = $extra;
         $this->full_keys[$namedform . '+' . $field] = $key;
     }
     $data = $this->getResults();
     if (!$this->processResults($data, $contentNode)) {
         I2CE::raiseError("Could not get results");
         return false;
     }
     $this->odf->mergeSegment($this->odf_row);
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Errors:\n" . $errors);
     }
     $this->odf->exportAsAttachedFile($template_file);
     exit;
     // we want to make sure there is no further output or that the $this->page->display() method is not called
 }
 /**
  * Display the report
  * @param DOMNode $contentNode The DOM node we wish to display into
  * @param boolean $processResults Defaults to true meaning we run through the results
  * @param mixed $controls.  If null (default), we display all the report controsl.  If string or an array of string, we only display the indicated controls
  * @returns boolean. true on sucess
  */
 public function display($contentNode, $processResults = true, $controls = null)
 {
     $this->saveDefaultView();
     $style = $this->getStyle();
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Got errors:\n{$errors}");
     }
     if ($this->transformsToHTML()) {
         $style = 'html';
     }
     $filename = $this->getFileName();
     $encoding = '';
     if (array_key_exists('HTTP_HOST', $_SERVER)) {
         header("Content-disposition: attachment; filename=\"{$filename}\"");
         $contentType = $this->getContentType();
         if ($contentType) {
             header("Content-type: {$contentType}");
         } else {
             //html snippet
             foreach ($this->template->getHeaders() as $header) {
                 header($header);
             }
         }
         // Flush the headers so the download box appears fast
         flush();
     }
     echo $this->generateExport();
     flush();
     exit;
     // we want to make sure there is no further output or that the $this->page->display() method is not called
 }
 public function generate($id, $stream = true)
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     if (!($doc = $this->get_doc_for_id($id)) instanceof DOMDocument) {
         I2CE::raiseError("Could not get document for " . $this->formRelationship->getPrimaryForm() . "|{$id}");
         return false;
     }
     $contents = $doc->saveXML($doc->documentElement);
     $transform_src = false;
     $transform_file = false;
     $trans_is_temp = false;
     if (!($this->request_exists('transform') && $this->request('transform') == 0)) {
         //allow request varible to turn of transform to check underlying data source easily
         if (array_key_exists('transform', $this->args) && is_string($this->args['transform'])) {
             $transform_src = $this->args['transform'];
         }
         if (is_string($transform_src) && strlen($transform_src)) {
             if ($transform_src[0] == '@') {
                 //it's a file.  search for it.
                 $file = substr($transform_src, 1);
                 if (!($transform_file = I2CE::getFileSearch()->search('XSLTS', $file))) {
                     I2CE::raiseError("Invalid transform file at {$file} => {$transform_file}\n" . print_r(I2CE::getFileSearch()->getSearchPath('XSLTS'), true));
                     return false;
                 }
             } else {
                 if (substr($transform_src, 0, 7) == 'file://') {
                     $transform_file = substr($transform_src, 7);
                 } else {
                     $trans_is_temp = true;
                     $transform_file = tempnam(sys_get_temp_dir(), 'XSL_REL_');
                     file_put_contents($transform_file, $transform_src);
                 }
             }
         }
     }
     if ($stream) {
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Got errors:\n{$errors}");
         }
         header('Content-Type: text/xml');
         flush();
         if ($transform_file) {
             $temp_file = tempnam(sys_get_temp_dir(), 'XML_REL_SINGLE_');
             file_put_contents($temp_file, $contents);
             $cmd = $this->get_transform_cmd($contents, $temp_file, $transform_file);
             passthru($cmd);
             unlink($temp_file);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
         } else {
             echo $contents;
         }
         exit(0);
     } else {
         if ($transform_file) {
             $temp_file = tempnam(sys_get_temp_dir(), 'XML_REL_SINGLE_');
             file_put_contents($temp_file, $contents);
             $cmd = $this->get_transform_cmd($contents, $temp_file, $transform_file);
             $trans = shell_exec($cmd);
             unlink($temp_file);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
             return $trans;
         } else {
             return $contents;
         }
     }
 }
Exemple #18
0
 /**
  * Gets the core system going.  
  * @param string $dsn dsn string to connect to the database
  * @param string $user_access_init the init string for the user access mechanism
  * @param string $site_module_file  the configttion file for the site module
  * @returns boolean.  True on sucess
  */
 public static function initializeDSN($dsn, $user_access_init, $site_module_file, $bring_up_system = true)
 {
     if (empty($dsn)) {
         self::raiseError("Please set the dsn string", E_USER_ERROR);
         if (!array_key_exists('HTTP_HOST', $_SERVER)) {
             //command line
             exit(11);
         } else {
             return false;
         }
     }
     $mdb2 = new MDB2();
     $dsn_info = $mdb2->parseDSN($dsn);
     if (I2CE_Dumper::dumpStaticURL($dsn_info['database'], 'file')) {
         exit;
     }
     if (!self::dbConnect($dsn_info)) {
         self::raiseError("Could not connect to the database");
         if (!array_key_exists('HTTP_HOST', $_SERVER)) {
             //command line
             exit(13);
         } else {
             return false;
         }
     }
     self::setupSession();
     $clear = false;
     if (!array_key_exists('HTTP_HOST', $_SERVER)) {
         //command line
         $clear = self::getRuntimeVariable('clear_cache', '0');
     } else {
         $URL = self::getAccessedBaseURL(false) . 'clear_cache.php';
         $clear = substr($_SERVER['REQUEST_URI'], 0, strlen($URL)) == $URL;
     }
     if ($clear) {
         $config = self::setupMagicData();
         $config->setIfIsSet(self::$email, "/I2CE/feedback/to");
         session_destroy();
         if (function_exists('apc_clear_cache')) {
             apc_clear_cache('user');
             I2CE::raiseError("Cleared APC User Cache");
         }
         I2CE::raiseError("Session destroyed");
         I2CE::getConfig()->clearCache();
         I2CE::raiseError("Magic data cleared -- Execution stopping");
         die(0);
     }
     $update = false;
     if (!array_key_exists('HTTP_HOST', $_SERVER)) {
         //command line
         $update = self::getRuntimeVariable('update', '0');
     } else {
         $URL = self::getAccessedBaseURL(false) . 'update.php';
         $update = substr($_SERVER['REQUEST_URI'], 0, strlen($URL)) == $URL;
     }
     if (self::siteInitialized()) {
         self::raiseError("Already initialized!", E_USER_WARNING);
         return true;
     }
     $db = MDB2::singleton();
     //get the instance we just created.
     if (!$update && $bring_up_system) {
         // just assume it is until we know otherwise.  This error
         // message to don't dumped to the screen.
         self::siteInitialized(true);
     }
     /*
     if (I2CE_Dumper::dumpStaticURL($db->database_name, 'file')) {
         exit();
     }
     */
     I2CE_Error::resetStoredMessages();
     if (empty($site_module_file)) {
         self::raiseError("Please set the site module's config file", E_USER_ERROR);
         if (!array_key_exists('HTTP_HOST', $_SERVER)) {
             //command line
             exit(14);
         } else {
             return false;
         }
     }
     $config = self::setupMagicData();
     $config->setIfIsSet(self::$email, "/I2CE/feedback/to");
     $site_module_file = I2CE_FileSearch::absolut($site_module_file, 1);
     self::setupFileSearch(array('MODULES' => array(dirname(dirname(__FILE__)), dirname($site_module_file)), 'CLASSES' => dirname(__FILE__)));
     self::setUserAccessInit($user_access_init, null, true);
     if ($update) {
         require_once 'I2CE_Updater.php';
         if (!I2CE_Updater::updateSite($site_module_file)) {
             if (array_key_exists('HTTP_HOST', $_SERVER)) {
                 die("<br/>Could not update site");
             } else {
                 I2CE::raiseError("\nCould not update site\n");
                 exit(15);
             }
         } else {
             if (!array_key_exists('HTTP_HOST', $_SERVER)) {
                 //command line
                 exit(0);
             }
         }
         return true;
     } else {
         if ($bring_up_system && !self::bringUpSystem($site_module_file)) {
             self::raiseError("Could not bring up system", E_USER_ERROR);
             exit(15);
         }
         I2CE::$ob_level = ob_get_level();
         return true;
     }
 }
 protected function export_results()
 {
     if (!($flow = $this->request('flow'))) {
         I2CE::raiseError("Bad flow");
         $this->error("Invalid Flow");
         return false;
     }
     $this->instantiateDisplay('Default', $this->view);
     if (!$this->display_obj instanceof I2CE_CustomReport_Display_mHero) {
         I2CE::raiseError("Bad display");
         $this->error("Invalid Display");
         return false;
     }
     I2CE::longExecution();
     $titles = $this->get_display_field_titles();
     I2CE::raiseError("TITLES=" . print_r($titles, true));
     $labels = $this->rapidpro->get_flow_field_labels($flow);
     $headers = array();
     if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && preg_match('/\\s+MSIE\\s+\\d\\.\\d;/', $_SERVER['HTTP_USER_AGENT'])) {
         $headers[] = "application/vnd.ms-excel";
     } else {
         $headers[] = "text/csv; charset=UTF-8";
     }
     $filename = 'mHero-' . '-' . $this->slug . '-export-' . date('Y') . '-' . date('m') . '-' . date('d') . '.csv';
     $headers[] = "Content-disposition: attachment; filename=\"{$filename}\"";
     $out = fopen("php://output", 'w');
     $keys = array('entityID' => 'Health Worker Registry Entity ID', 'iHRIS_link' => 'iHRIS Source Record');
     $keys = array_merge($keys, $labels);
     $keys = array_merge($keys, $titles);
     I2CE::raiseError("KEYS=" . print_r($keys, true));
     $csd_uuids = $this->display_obj->get_csd_uuids();
     $person_ids = array_flip($csd_uuids);
     $assigning_authority = $this->host . '/' . $this->slug;
     $contacts = $this->rapidpro->getOtherIDs($this->csd_host, $csd_uuids, $assigning_authority);
     $contact_list = array();
     foreach ($contacts as $entityID => $contact) {
         if (!is_array($contact) || !array_key_exists('otherID', $contact) || !is_array($contact['otherID']) || count($contact['otherID']) != 1 || !reset($contact['otherID']) || !is_array($otherID = current($contact['otherID'])) || !array_key_exists('value', $otherID) || !($rapidpro_id = $otherID['value'])) {
             continue;
         }
         $contact_list[$rapidpro_id] = $entityID;
     }
     I2CE::raiseError(print_r($contacts, true));
     I2CE::raiseError(print_r($contact_list, true));
     $runs = $this->rapidpro->getFlowValues($flow);
     //would be better if we could put the streaming function as a callback after each hit on rapidpro
     $results = array();
     foreach ($runs as $run) {
         I2CE::raiseMessage($run['contact']);
         if (!is_array($run) || !array_key_exists('contact', $run) || !($rapidpro_id = $run['contact']) || !array_key_exists($rapidpro_id, $contact_list) || !($entityID = $contact_list[$rapidpro_id]) || !array_key_exists('values', $run) || !is_array($run['values'])) {
             continue;
         }
         $values = array();
         foreach ($run['values'] as $val_set) {
             if (!is_array($val_set) || !array_key_exists('label', $val_set) || !($label = $val_set['label']) || !array_key_exists('text', $val_set)) {
                 continue;
             }
             $values[$label] = $val_set['text'];
         }
         $results[$entityID] = $values;
     }
     I2CE::raiseError(print_r($results, true));
     if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
         I2CE::raiseError("Got errors:\n{$errors}");
     }
     I2CE::longExecution();
     foreach ($headers as $header) {
         header($header);
     }
     fputcsv($out, $keys);
     foreach ($results as $entityID => $values) {
         if (!array_key_exists($entityID, $person_ids) || !($person_id = $person_ids[$entityID])) {
             continue;
         }
         $iHRIS_link = I2CE::getAccessedBaseURL() . 'view?id=' . $person_id;
         $fields = array('entityID' => $entityID, 'iHRIS_link' => $iHRIS_link);
         foreach ($labels as $label) {
             if (!array_key_exists($label, $values)) {
                 $fields[] = '';
             } else {
                 $fields[] = $values[$label];
             }
         }
         $fields = array_merge($fields, $this->get_display_fields($person_id));
         foreach ($titles as $title => $label) {
             if (!array_key_exists($title, $fields) || !is_scalar($val = $fields[$title])) {
                 $fields[$title] = '';
             } else {
                 $fields[$title] = $val;
             }
         }
         fputcsv($out, $fields);
         flush();
     }
     fclose($out);
     exit(0);
 }
 public function generate_for_ids($ids, $stream = true)
 {
     $temp_file = tempnam(sys_get_temp_dir(), 'XML_REL_');
     file_put_contents($temp_file, "<?xml version='1.0'?><relationshipCollection name='" . $this->formRelationship->getPrimaryFormName() . "'>\n", FILE_APPEND);
     file_put_contents($temp_file, "<!-- Contains " . count($ids) . " records -->\n", FILE_APPEND);
     I2CE::raiseError("get XML representation for " . count($ids) . " records");
     $div = 1;
     if (count($ids) > 0) {
         $part = count($ids) / 10;
     }
     $rec = 0;
     $div = $part;
     foreach ($ids as $id) {
         $rec++;
         if ($rec > $div) {
             I2CE::raiseError("Completed " . $div / $part * 10 . " %");
             $div += $part;
         }
         I2CE::longExecution(array("max_execution_time" => 1800));
         $doc = $this->get_doc_for_id($id);
         file_put_contents($temp_file, "<!-- Record #: " . $rec . "-->", FILE_APPEND);
         file_put_contents($temp_file, $doc->saveXML($doc->documentElement) . "\n", FILE_APPEND);
     }
     I2CE::longExecution(array("max_execution_time" => 1800));
     file_put_contents($temp_file, "</relationshipCollection>", FILE_APPEND);
     $transform_src = false;
     $transform_file = false;
     $trans_is_temp = false;
     if (!($this->request_exists('transform') && $this->request('transform') == 0)) {
         //allow request varible to turn of transform to check underlying data source easily
         if (array_key_exists('transform', $this->args) && is_string($this->args['transform'])) {
             $transform_src = $this->args['transform'];
         }
         if (is_string($transform_src) && strlen($transform_src)) {
             I2CE::raiseError("Looking at {$transform_src}");
             if ($transform_src[0] == '@') {
                 //it's a file.  search for it.
                 $file = substr($transform_src, 1);
                 if (!($transform_file = I2CE::getFileSearch()->search('XSLTS', $file))) {
                     I2CE::raiseError("Invalid transform file at {$file} => {$transform_file}\n" . print_r(I2CE::getFileSearch()->getSearchPath('XSLTS'), true));
                     exit(0);
                 }
             } else {
                 if (substr($transform_src, 0, 7) == 'file://') {
                     $transform_file = substr($transform_src, 7);
                 } else {
                     $transform_file = tempnam(sys_get_temp_dir(), 'XSL_REL_');
                     $trans_is_temp = true;
                     file_put_contents($transform_file, $transform_src);
                 }
             }
         }
     }
     if ($stream) {
         if ($errors = I2CE_Dumper::cleanlyEndOutputBuffers()) {
             I2CE::raiseError("Got errors:\n{$errors}");
         }
         header('Content-Type: text/xml');
         if ($transform_file) {
             $cmd = "xsltproc " . escapeshellarg($transform_file) . " " . escapeshellarg($temp_file);
             I2CE::raiseError("Transforming with: {$cmd}");
             passthru($cmd);
             unlink($temp_file);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
         } else {
             I2CE::raiseError("Reading: {$temp_file}");
             readfile($temp_file);
             unlink($temp_file);
         }
         exit(0);
     } else {
         if ($transform_file) {
             $cmd = "xsltproc " . escapeshellarg($transform_file) . " " . escapeshellarg($temp_file);
             I2CE::raiseError("Transforming with: {$cmd}");
             $contents = shell_exec($cmd);
             if ($trans_is_temp) {
                 unlink($transform_file);
             }
             unlink($temp_file);
             return $contents;
         } else {
             I2CE::raiseError("Reading: {$temp_file}");
             $contents = file_get_contents($temp_file);
             unlink($temp_file);
             return $contents;
         }
     }
 }