コード例 #1
0
 public function get_display_fields()
 {
     I2CE::longExecution();
     $this->unsetPaging();
     if (!is_array($data = $this->getResults()) || !array_key_exists('results', $data) || !($results = $data['results'])) {
         I2CE::raiseError("No data");
         return array();
     }
     $person_ids = array();
     $id = 'primary_form+id';
     $uuid = 'primary_form+csd_uuid';
     $display_fields = array();
     $titles = $this->get_display_field_titles();
     while (is_array($row = $results->fetchRow(MDB2_FETCHMODE_ASSOC))) {
         I2CE::longExecution();
         if (!array_key_exists('primary_form+id', $row) || !($person_id = $row['primary_form+id'])) {
             I2CE::raiseError("Bad:" . print_r($row, true));
             continue;
         }
         $data = array();
         foreach ($titles as $formfield => $label) {
             ///this is just to ensure the same order as the display name of the fields
             if (!array_key_exists($formfield, $row)) {
                 continue;
             }
             $data[$formfield] = $row[$formfield];
         }
         $display_fields[$person_id] = $data;
     }
     $results->free();
     return $display_fields;
 }
コード例 #2
0
 protected function resaveTrainings()
 {
     $user = new I2CE_User();
     $ff = I2CE_FormFactory::instance();
     $ids = I2CE_FormStorage::search('person_scheduled_training_course');
     foreach ($ids as $id) {
         I2CE::longExecution();
         //to make sure we don't time out
         if (!($pstc = $ff->createContainer(array('person_scheduled_training_course', $id))) instanceof iHRIS_Person_Scheduled_Training_Course) {
             return false;
             //something is wrong
         }
         $pstc->populate();
         //populate will recacluate the average field
         $pstc->save($user);
         //saves the new calculated average field to the databse
         $pstc->cleanup();
         //free up memory
     }
     return true;
 }
コード例 #3
0
 protected function doRemap($form, $field, $id)
 {
     $obj = $this->ff->createContainer($id);
     if (!$obj instanceof I2CE_List) {
         $this->pushError("ID {$id} does not refer to a list");
         //needs to be localized
         return false;
     }
     $obj->populate();
     $newform = '0';
     $newid = '0';
     $rField = $obj->getField('remap');
     if (!$rField instanceof I2CE_FormField_REMAP || !($newform = $rField->getMappedForm()) || !($newid = $rField->getMappedID())) {
         $this->pushError("No remapping data has been set for {$id} [{$newform}|{$newid}]" . get_class($rField));
         return false;
     }
     $where = array('operator' => 'FIELD_LIMIT', 'field' => $field, 'style' => 'equals', 'data' => array('value' => $id));
     if (($count = count($remapIDs = I2CE_FormStorage::search($form, false, $where))) < 1) {
         $this->pushMessage("No fields found to remap");
         return true;
     }
     $this->pushCount($count);
     $exec = array('max_execution_time' => 20 * 60, 'memory_limit' => 256 * 1048576);
     $user = new I2CE_User();
     $success = true;
     foreach ($remapIDs as $i => $remapID) {
         I2CE::longExecution($exec);
         if (!($remapObj = $this->ff->createContainer($form . '|' . $remapID)) instanceof I2CE_Form) {
             $this->pushMessage("Could not create {$form}|{$remapID}", $i + 1);
             $success = false;
             continue;
         }
         $remapObj->populate();
         if (!($fieldObj = $remapObj->getField($field)) instanceof I2CE_FormField_MAP) {
             $this->pushMessage("Field {$field} is not a map field", $i + 1);
             $success = false;
             $remapObj->cleanup();
             continue;
         }
         $fieldObj->setFromDB($newform . '|' . $newid);
         $this->pushMessage("Remapping {$field} in  {$form}|{$remapID} to be {$newform}|{$newid}", $i + 1);
         if (!$remapObj->save($user)) {
             $success = false;
             $this->pushMessage("Could not save {$field} in {$form}|{$remapID} to be {$newform}|{$newid}", $i + 1);
         } else {
             $this->pushMessage("Remapped {$field} in {$form}|{$remapID} to be {$newform}|{$newid}", $i + 1);
         }
         $remapObj->cleanup();
     }
     return $success;
 }
コード例 #4
0
 /**
  *Loads in the requeted data from the relationship
  * @returns boolean  True on success
  */
 protected function loadData($as_iterator = true)
 {
     $fields = $this->getFields();
     $ordering = $this->getOrdering();
     I2CE::longExecution(array("max_execution_time" => 1800));
     $this->data = $this->formRelationship->getFormData($this->primObj->getName(), $this->primObj->getId(), $fields, $ordering, $as_iterator);
     if ($as_iterator) {
         if (!$this->data instanceof I2CE_RelationshipData) {
             I2CE::raiseError("No data");
             return false;
         }
     } else {
         if (!is_array($this->data)) {
             return false;
         }
     }
     return true;
 }
コード例 #5
0
 /**
  *Abstract method to render the form. Makes sure all ducks are in a row
  * @returns boolean true on sucess.
  */
 public function render()
 {
     if (!is_string($this->std_form) || strlen($this->std_form) == 0) {
         I2CE::raiseError("No standard printed form set");
         return false;
     }
     $this->stdConfig = I2CE::getConfig()->traverse('/modules/PrintedForms/forms/' . $this->std_form, false);
     if (!$this->stdConfig instanceof I2CE_MagicDataNode) {
         I2CE::raiseError("No standard printed form   /modules/PrintedForms/forms/" . $this->std_form);
         return false;
     }
     if (!$this->stdConfig->setIfIsSet($relationship, 'relationship')) {
         I2CE::raiseError("No relationship set");
         return false;
     }
     try {
         $this->rel = new I2CE_FormRelationship($relationship, $this->base_rel_config);
     } catch (Exception $e) {
         I2CE::raiseError("Could not instatiate relationship {$relationship}");
         return false;
     }
     $this->layoutOptions = array('encoding' => 'ASCII', 'hyphenation_file' => 'hyph_en_US.dic', 'orientation' => 'P', 'size' => 'A4', 'rows' => 1, 'cols' => 1, 'horiz_pad' => 10, 'horiz_pad_border' => 0, 'vert_pad' => 10, 'vert_pad_border' => 0);
     if ($this->stdConfig->is_parent('layout_details')) {
         I2CE_Util::merge_recursive($this->layoutOptions, $this->stdConfig->getAsArray("layout_details"));
     }
     if (!in_array($this->layoutOptions['orientation'], array('P', 'L'))) {
         $this->layoutOptions['orientation'] = 'P';
     }
     $paper_sizes = array('A0' => array(841, 1189), 'A1' => array(594, 841), 'A2' => array(420, 594), 'A3' => array(297, 420), 'A4' => array(210, 297), 'A5' => array(148, 210), 'A6' => array(105, 148), 'A7' => array(74, 105), 'A8' => array(52, 74), 'A9' => array(37, 52), 'A10' => array(26, 37), 'B0' => array(1000, 1414), 'B1' => array(707, 1000), 'B2' => array(500, 707), 'B3' => array(353, 500), 'B4' => array(250, 353), 'B5' => array(176, 350), 'B6' => array(125, 176), 'B7' => array(88, 125), 'B8' => array(62, 88), 'B9' => array(44, 62), 'B10' => array(31, 44), 'C0' => array(917, 1297), 'C1' => array(648, 917), 'C2' => array(458, 648), 'C3' => array(324, 458), 'C4' => array(229, 324), 'C5' => array(162, 229), 'C6' => array(114, 162), 'C7' => array(81, 114), 'C8' => array(57, 81), 'C9' => array(40, 57), 'C10' => array(28, 40), 'LETTER' => array(216, 279), 'LEGAL' => array(216, 356), 'JUNIOR_LEGAL' => array(203, 127), 'LEDGER' => array(432, 279), 'TABLOID' => array(279, 432));
     $this->layoutOptions['size'] = strtoupper($this->layoutOptions['size']);
     if (!in_array($this->layoutOptions['size'], array_keys($paper_sizes))) {
         $this->layoutOptions['size'] = 'A4';
     }
     if ($this->layoutOptions['orientation'] == 'P') {
         $this->layoutOptions['paper_size'] = $paper_sizes[$this->layoutOptions['size']];
     } else {
         $this->layoutOptions['paper_size'] = array_reverse($paper_sizes[$this->layoutOptions['size']]);
     }
     if (!array_key_exists('border', $this->layoutOptions)) {
         if ($this->layoutOptions['rows'] == 1 && $this->layoutOptions['cols'] == 1) {
             $this->layoutOptions['border'] = 0;
         } else {
             $this->layoutOptions['border'] = 1;
         }
     }
     $this->layoutOptions['border'] = (int) $this->layoutOptions['border'];
     if ($this->layoutOptions['border'] < 0) {
         $this->layoutOptions['border'] = 0;
     }
     $this->layoutOptions['horiz_pad_border'] = (int) $this->layoutOptions['horiz_pad_border'];
     if ($this->layoutOptions['horiz_pad_border'] < 0) {
         $this->layoutOptions['horiz_pad_border'] = 0;
     }
     $this->layoutOptions['vert_pad_border'] = (int) $this->layoutOptions['vert_pad_border'];
     if ($this->layoutOptions['vert_pad_border'] < 0) {
         $this->layoutOptions['vert_pad_border'] = 0;
     }
     $this->layoutOptions['horiz_pad'] = (int) $this->layoutOptions['horiz_pad'];
     if ($this->layoutOptions['horiz_pad'] < 0) {
         $this->layoutOptions['horiz_pad'] = 10;
     }
     $this->layoutOptions['vert_pad'] = (int) $this->layoutOptions['vert_pad'];
     if ($this->layoutOptions['vert_pad'] < 0) {
         $this->layoutOptions['vert_pad'] = 10;
     }
     $this->layoutOptions['rows'] = (int) $this->layoutOptions['rows'];
     $this->layoutOptions['cols'] = (int) $this->layoutOptions['cols'];
     if ($this->layoutOptions['rows'] < 1) {
         I2CE::raiseError("Invalid rows");
         return false;
     }
     if ($this->layoutOptions['cols'] < 1) {
         I2CE::raiseError("Invalid cols");
         return false;
     }
     $this->layoutOptions['form_width'] = (int) (($this->layoutOptions['paper_size'][0] - 2 * $this->layoutOptions['horiz_pad'] - $this->layoutOptions['border'] * ($this->layoutOptions['cols'] + 1) - 2 * $this->layoutOptions['horiz_pad_border'] * $this->layoutOptions['cols']) / $this->layoutOptions['cols']);
     $this->layoutOptions['form_height'] = (int) (($this->layoutOptions['paper_size'][1] - 2 * $this->layoutOptions['vert_pad'] - $this->layoutOptions['border'] * ($this->layoutOptions['rows'] + 1) - 2 * $this->layoutOptions['vert_pad_border'] * $this->layoutOptions['rows']) / $this->layoutOptions['rows']);
     if ($this->layoutOptions['form_width'] < 10) {
         I2CE::raiseError("Not enough width");
         return false;
     }
     if ($this->layoutOptions['form_height'] < 10) {
         I2CE::raiseError("Not enough height");
         return false;
     }
     $this->content = $this->stdConfig->getAsArray('content');
     $forms = array();
     foreach ($this->ids as $id) {
         if (!is_string($id)) {
             continue;
         }
         $fs = $this->rel->getFormsSatisfyingRelationship($id);
         if (!is_array($fs) || count($fs) == 0) {
             continue;
         }
         $forms[$id] = $fs;
     }
     if (count($forms) == 0) {
         I2CE::raiseError("No valid forms");
         return false;
     }
     $this->forms = $forms;
     $textProps = array('font' => 'helvetica', 'style' => '', 'size' => 12, 'alignment' => 'L', 'color' => '#000000', 'bg_color' => 'none', 'style' => '');
     if ($this->stdConfig->is_parent('text_properties')) {
         I2CE_Util::merge_recursive($textProps, $this->stdConfig->getAsArray("text_properties"));
     }
     $this->validateTextProps($textProps);
     I2CE::longExecution();
     return $this->_render($textProps);
 }
コード例 #6
0
 protected function createAltConfig($update_from_config)
 {
     $hash = '2245023265ae4cf87d02c8b6ba991139';
     //the hash of the root node
     //first test to see if the alt config table is there for some reason.
     $db = MDB2::singleton();
     $qry = 'SHOW TABLES LIKE "config_alt"';
     $result = $db->query($qry);
     if (I2CE::pearError($result, "Cannot access database")) {
         return false;
     }
     if ($result->numRows() > 0) {
         I2CE::raiseError("Alt Config table has already been created");
         $qry = "SELECT count(*) as count FROM `config_alt` WHERE `path_hash` = '{$hash}'";
         $result = $db->query($qry);
         if (I2CE::pearError($result, "Cannot access config_alt")) {
             return false;
         }
         if ($row = $result->fetchRow()) {
             if ($row->count == 1) {
                 I2CE::raiseError("Alt config has been created and seeded");
                 return true;
             }
         }
     }
     if ($update_from_config) {
         //now see if the tmp alt config table is there and if so drop it.
         $qry = 'SHOW TABLES LIKE "config_alt_tmp"';
         $result = $db->query($qry);
         if (I2CE::pearError($result, "Cannot access database")) {
             return false;
         }
         if ($result->numRows() > 0) {
             I2CE::raiseError("Temporary Alt Config table has already been created -- Dropping it");
             $qry = 'DROP TABLE  `config_alt_tmp`';
             if (I2CE::pearError($db->query($qry), "Cannot drop temporary alternative config table")) {
                 return false;
             }
         }
         $create = 'config_alt_tmp';
     } else {
         $create = 'config_alt';
     }
     $qrs = array("CREATE TABLE IF NOT EXISTS  `{$create}`  (\n  `path_hash` char(32) NOT NULL,\n  `parent` text NOT NULL,\n  `name` text  NOT NULL,\n  `type` tinyint(4) NOT NULL,\n  `value` longtext CHARACTER SET utf8 default NULL,\n  PRIMARY KEY  (`path_hash`),\n  KEY  (`parent` (130) ),\n  KEY `path` ( `parent` ( 130 ), `name` (30) )\n) ENGINE=InnoDB DEFAULT CHARSET=utf8", "INSERT INTO `{$create}` (`path_hash`,`parent`,`name`,`type`,`value`) VALUE ('{$hash}','','',0,NULL)");
     foreach ($qrs as $qry) {
         $result = $db->query($qry);
         if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
             I2CE::raiseError("Could not initialize temporary alternate config table");
             return false;
         }
     }
     if (!$update_from_config) {
         return true;
     }
     $qry = 'SHOW TABLES LIKE "config"';
     $result = $db->query($qry);
     if (I2CE::pearError($result, "Cannot access database")) {
         return false;
     }
     if ($result->numRows() == 0) {
         I2CE::raiseError("Attempting to update to alternative config table from existing config table, but the config table does not exist");
         return false;
     }
     I2CE::longExecution();
     I2CE::raiseError("Inserting entries into config_alt table from config table");
     $qry = "REPLACE  INTO config_alt_tmp(path_hash,parent,name,type,value) SELECT \n            hash AS path_hash,\n            IF ( locate('/',path) > 0 , CONCAT('/',SUBSTR(path,8,length(path) -7 - locate('/', reverse(path)))) , IF (locate(':',path), '/','' ) ) as parent,\n            IF ( locate('/',path) > 0 , SUBSTR(path,length(path) - locate('/', reverse(path)) +2  ), IF (locate(':',path),SUBSTR(path,locate(':',path)+1),'') ) as name\n            ,type,value\nfrom config WHERE ( locate(':',path) > 0 OR path = 'config' )";
     if (I2CE::pearError($db->query($qry), "Cannot update alternative config table from existing table")) {
         return false;
     }
     $qry = "RENAME TABLE `config_alt_tmp` TO `config_alt`";
     if (I2CE::pearError($db->query($qry), "Cannot rename temporary alternative config table")) {
         return false;
     }
     return $this->setupMagicDataStorage();
 }
コード例 #7
0
 protected function generateTemplate()
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     if (!class_exists('I2CE_Odf')) {
         I2CE::raiseError("Please turn on the printed forms module");
         return false;
     }
     $odf_config = array('DELIMITER_LEFT' => '{{{', 'DELIMITER_RIGHT' => '}}}', 'ZIP_PROXY' => 'PhpZipProxy');
     $odf = new I2CE_Odf($this->template_file, $odf_config);
     $segment_style = 'global';
     if (array_key_exists('segment_style', $this->args) && is_string($this->args['segment_style'])) {
         $segment_style = $this->args['segment_style'];
     }
     $method = 'generateTemplate_' . $segment_style;
     if (!$this->_hasMethod($method)) {
         I2CE::raiseError("Invalid method: {$method}");
         return false;
     }
     $this->{$method}($odf);
     I2CE::raiseError("Outputing template");
     $this->outputTemplate($odf, basename($this->template_file, '.odt'));
 }
コード例 #8
0
 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;
         }
     }
 }
コード例 #9
0
ファイル: I2CE.php プロジェクト: apelon-ohie/ihris-site
 /**
  * Get the system status.  http://www.ursula1000.com/
  * @returns string 'gogo' means we are good. 'needs_installation'  means we need to initialize. 'needs_upgrade'
  */
 public static function allSystemsAreGoGo($site_module_file, $check_time = false)
 {
     $site_module_file = I2CE_FileSearch::realPath($site_module_file);
     $config = self::getConfig();
     $site_module = '';
     $config->setIfIsSet($site_module, '/config/site/module');
     $mod_factory = I2CE_ModuleFactory::instance();
     $installed = '';
     $config->setIfIsSet($installed, "/config/site/installation");
     if ($installed == '') {
         return 'needs_install';
     }
     if (!$site_module) {
         self::raiseError("Cannot determine what your site is.  This is bad.\n({$site_module_file})", E_USER_ERROR);
         return 'no_site';
     }
     if (substr($installed, 0, 11) == 'in_progress') {
         if (array_key_exists('HTTP_HOST', $_SERVER)) {
             self::raiseError("Warning: Trying to access the site while update is in progress. Do you know what you are doing?");
         } else {
             self::raiseError("Warning: Trying to access the site while update is in progress. Run --update=1 --force-restart=1 to restart");
         }
         return $installed;
     } else {
         if ($installed == 'done') {
             $previous_site_file = '';
             if ($config->setIfIsSet($previous_site_file, '/config/data/' . $site_module . '/file')) {
                 $previous_site_file = I2CE_FileSearch::realPath($previous_site_file);
                 if ($previous_site_file != $site_module_file) {
                     I2CE::raiseError("Need reinstall ({$previous_site_file}) != ({$site_module_file}) for site module {$site_module}");
                     return 'needs_reinstall';
                 }
             }
             $mod_factory = I2CE_ModuleFactory::instance();
             if (!$mod_factory->isEnabled($site_module)) {
                 return 'needs_reenable';
             }
             //$installed == 'done' and the site module/site module file are good.  This should be the 'usual state of affairs'
             $times = array();
             $config->setIfIsSet($times, '/I2CE/update/times', true);
             if (!isset($times['stale'])) {
                 $times['stale'] = 10;
             }
             if (!$check_time) {
                 if ($times['stale'] < 0 || !isset($times['last'])) {
                     $check_time = true;
                 } else {
                     if (isset($times['last'])) {
                         $check_time = time() - $times['last'] > $times['stale'];
                     }
                 }
             }
             if ($check_time) {
                 I2CE::longExecution(null, false);
                 //we are due to check the config files/modules for updates
                 $config->__set("/I2CE/update/times/last", time());
                 $updates = $mod_factory->getOutOfDateConfigFiles();
                 $config->__set("/I2CE/update/times/last", time());
                 if (count($updates['updates']) + count($updates['removals']) > 0) {
                     return 'needs_upgrade';
                 }
             }
             return 'done';
         } else {
             self::raiseError("Unknown installation status:" . $installed, E_USER_ERROR);
             return 'unknown';
         }
     }
 }
コード例 #10
0
 /**
  * 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;
 }
コード例 #11
0
 /**
  *Abstract method to render the form. Makes sure all ducks are in a row
  * @returns boolean true on sucess.
  */
 public function render()
 {
     if (count($this->ids) != 1) {
         I2CE::raiseError("Exactly one ID must be specifed (currently)");
         return false;
     }
     if (!is_string($this->std_form) || strlen($this->std_form) == 0) {
         I2CE::raiseError("No standard printed form set");
         return false;
     }
     $this->stdConfig = I2CE::getConfig()->traverse('/modules/PrintedForms/forms/' . $this->std_form, false);
     if (!$this->stdConfig instanceof I2CE_MagicDataNode) {
         I2CE::raiseError("No standard printed form   /modules/PrintedForms/forms/" . $this->std_form);
         return false;
     }
     if (!$this->stdConfig->setIfIsSet($relationship, 'relationship')) {
         I2CE::raiseError("No relationship set");
         return false;
     }
     try {
         $this->rel = new I2CE_FormRelationship($relationship, $this->base_rel_config);
     } catch (Exception $e) {
         I2CE::raiseError("Could not instatiate relationship {$relationship}");
         return false;
     }
     $template = false;
     $template_upload = false;
     if ($this->stdConfig->setIfIsSet($template_upload, 'template_upload', true) && array_key_exists('content', $template_upload) && $template_upload['content'] && array_key_exists('name', $template_upload) && $template_upload['name']) {
         $name = $template_upload['name'];
         $pos = strrpos($name, '.');
         if ($pos !== false) {
             $name = substr($name, 0, $pos);
         }
         $this->template_file = tempnam(sys_get_temp_dir(), basename($name . '_')) . '.odt';
         file_put_contents($this->template_file, $template_upload['content']);
     } else {
         if ($this->stdConfig->setIfIsSet($template, 'template')) {
             $this->template_file = I2CE::getFileSearch()->search('ODT_TEMPLATES', $template);
             if (!$this->template_file) {
                 I2CE::raiseError("No template file found from {$template}");
                 return false;
             }
         } else {
             I2CE::raiseError("No template  set");
             return false;
         }
     }
     $template_contents = new ZipArchive();
     if ($template_contents->open($this->template_file) !== TRUE) {
         I2CE::raiseError("Could not extract odt file");
         return;
     }
     $this->template_vars = array();
     for ($i = 0; $i < $template_contents->numFiles; $i++) {
         $stats = $template_contents->statIndex($i);
         if ($stats['name'] != 'content.xml') {
             continue;
         }
         $matches = array();
         //pull out all the template variables for processing.
         preg_match_all('/{{{([0-9a-zA-Z_\\-\\+\\,\\=\\.]+(\\(.*?\\))?)}}}/', $template_contents->getFromIndex($i), $matches, PREG_SET_ORDER);
         foreach ($matches as $match) {
             if (!is_array($match) || count($match) < 2 || !is_string($match[1]) || strlen($match[1]) == 0) {
                 continue;
             }
             $this->template_vars[] = $match[1];
         }
         $this->template_vars = array_unique($this->template_vars);
     }
     $this->content = $this->stdConfig->getAsArray('content');
     $forms = array();
     foreach ($this->ids as $id) {
         if (!is_string($id)) {
             continue;
         }
         $fs = $this->rel->getFormsSatisfyingRelationship($id);
         if (!is_array($fs) || count($fs) == 0) {
             continue;
         }
         $forms[$id] = $fs;
     }
     if (count($forms) == 0) {
         I2CE::raiseError("No valid forms");
         return false;
     }
     $this->forms = $forms;
     $textProps = array();
     I2CE::longExecution();
     $success = $this->_render($textProps);
     return $success;
 }
コード例 #12
0
ファイル: wikidoc.php プロジェクト: apelon-ohie/ihris-site
                break;
            }
        }
    }
    if (!$class_found) {
        $debug = debug_backtrace();
        $msg = "Cannot find the defintion for class ({$class_name})";
        if (array_key_exists(1, $debug) && array_key_exists('line', $debug[1])) {
            $msg .= "called from  line " . $debug[1]['line'] . ' of file ' . $debug[1]['file'];
        }
        $msg .= "\nSearch Path is:\n" . print_r(I2CE::getFileSearch()->getSearchPath('CLASSES'), true);
        //        I2CE::raiseError( $msg, E_USER_NOTICE);
    }
}
spl_autoload_register('i2ce_class_autoload');
I2CE::longExecution(array('memory_limit' => 512 * 1048576));
/*****************************************
 *  make the module list pages
 *****************************************/
$module_packages = array();
$wout = array();
$wout['all'] = "__PAGE:iHRIS Module List\nThis is a list of all the modules available in the iHRIS Suite\n";
foreach ($packages as $pkg => $info) {
    $wout[$pkg] = '__PAGE:' . $info['name'] . " Module List\n";
    $wout[$pkg] .= "This is a list of all modules available in version " . $versions[$pkg] . ' of the package [' . $info['bzr'] . ' ' . $info['name'] . "]\n";
}
$comps = array('atleast' => 'at least ', 'atmost' => 'at most ', 'exactly' => 'exactly ', 'greaterthan' => 'greater than ', 'lessthan' => 'less than ');
ksort($found_modules, SORT_STRING);
$classObjs = array();
$fuzzys = array();
$fuzzys_CLI = array();
コード例 #13
0
 /**
  * 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
 }
コード例 #14
0
 /**
  * Checks to make sure there is the given index on the last_entry.  If it does not exist it adds it.
  * @param string $index_name 
  * @param mixed $fields.  Either a string or array of string, the fields we want to make an index on
  *
  * If the field names need backtics, you are required to provide them
  */
 protected function createIndexOnLastEntry($index_name, $fields)
 {
     if (is_string($fields)) {
         $fields = array($fields);
     }
     if (!is_array($fields) || count($fields) == 0) {
         I2CE::raiseError("Invalid fields");
         return false;
     }
     $db = MDB2::singleton();
     $qry = "SELECT  null FROM information_schema.statistics WHERE\ntable_schema = '{$db->database_name}'\nand table_name = 'last_entry'\nand index_name = '{$index_name}'";
     $result = $db->query($qry);
     if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
         return false;
     }
     if ($result->numRows() > 0) {
         //the index has already been created.
         return true;
     }
     //the index has not been created.
     I2CE::longExecution();
     //it may take a shilw
     I2CE::raiseError("Creating index '{$index_name}' on the field(s) " . implode(",", $fields) . " of  last_entry.  This may take a long time if you have many records.");
     $qry = "CREATE INDEX {$index_name} ON last_entry (" . implode(',', $fields) . ")";
     $result = $db->query($qry);
     if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
         return false;
     }
     return true;
 }
コード例 #15
0
 /**
  * Generate the the exported report
  * @returns string
  */
 public function generateExport()
 {
     I2CE::longExecution(array("max_execution_time" => 1800));
     $style = $this->getStyle();
     $formfields = $this->getDisplayFieldsData();
     $headers = array('#');
     foreach ($formfields as $formfield => $data) {
         if (!$data) {
             continue;
         }
         $headers[$formfield] = $data['header'];
     }
     $this->cols = array_keys($headers);
     switch ($style) {
         case 'xml':
             $post = " </reportData>\n</ihrisReport>\n";
             array_shift($this->cols);
             $pre = $this->getXMLMetaData($headers);
             break;
         case 'tab':
             $post = '';
             $pre = $this->processResultRowArray($headers);
             break;
         case 'csv':
             $post = '';
             $pre = $this->processResultRowArray($headers);
             break;
         case 'rawjson':
             $post = '}';
             unset($headers[0]);
             $pre = '{"headers":' . json_encode($headers) . ',"data":';
             break;
         case 'json':
             $post = ']';
             unset($headers[0]);
             $pre = '[' . json_encode(array_values($headers));
             break;
         default:
             //html snippet
             $name = addslashes(str_replace(array(' ', "\n", "\t"), array('_', ' ', '_'), $this->config->display_name));
             $pre = "<table id='" . addslashes($this->view) . " name='{$name}'>\n";
             $post = '</table>';
             $pre .= $this->processResultRowArray($headers);
             break;
     }
     $data = $this->getResults();
     $out = $this->processResults($data, $resultsNode = null);
     $out = $pre . $out . $post;
     if ($style == 'xml' && $this->transform) {
         $xmlDoc = new DOMDocument();
         if (!@$xmlDoc->loadXML($out)) {
             I2CE::raiseError("Could not load source document");
             return $out;
         }
         $xslDoc = new DOMDocument();
         if (!array_key_exists('xslts', $this->defaultOptions) || !is_array($this->defaultOptions['xslts']) || !@$xslDoc->loadXML($this->defaultOptions['xslts'][$this->transform]['definition'])) {
             I2CE::raiseError("Could not load transform");
             return false;
         }
         $proc = new XSLTProcessor();
         if (!@$proc->importStylesheet($xslDoc)) {
             I2CE::raiseError("Could not import style sheet");
             return false;
         }
         if (($out = @$proc->transformToXML($xmlDoc)) === false) {
             I2CE::raiseError("Could not transform accoring to xsl");
             return false;
         }
     }
     switch ($this->compression) {
         case 'bz2':
             return bzcompress($out);
         case 'gz':
             return gzencode($out, 9);
         case 'zip':
             if (!@class_exists('ZipArchive', false)) {
                 I2CE::raiseError("zip not present");
                 $this->compression = false;
                 break;
             }
             $zip = new ZipArchive();
             $temp_file = tempnam(sys_get_temp_dir(), 'EXPORT_ZIP');
             if ($zip->open($temp_file) !== true) {
                 I2CE::raiseError("Could not ceaete zip on {$temp_file}");
                 $this->compression = false;
                 break;
             }
             $filename = $this->getFileName(null, false);
             $zip->addFromString($filename, $out);
             $zip->close();
             $out = file_get_contents($temp_file);
             break;
         default:
             break;
     }
     return $out;
 }
コード例 #16
0
 /**
  * Migrate field data from an old setMap reference to a new MAP form field type.
  * The old data should have been saved in a migrate_data magic data (see {@link storeMigrateData}).
  * @param string $form_name
  * @param array $field_list The list of fields that need to be changed as an array of field => map_form.
  *                          Optionally the field list can be:
  *                          array( "field" => array( "prev_field" => "prev_map_form" ) )
  *                          The field will get the old value from the list of fields (with mapped forms)
  *                          for when the field name was changed.
  * @param string $migrate_path Where the migrate data has been saved.
  * @param I2CE_User $user The user to save the new form field.
  * @return boolean
  */
 public static function migrateField($form_name, $field_list, $migrate_path, $user)
 {
     I2CE::longExecution();
     $factory = I2CE_FormFactory::instance();
     $factory->clearFieldData($form_name);
     $storage = self::getStorageMechanism($form_name, true);
     $migrate_node = I2CE::getConfig()->traverse($migrate_path, true, false);
     $field_node = $migrate_node->traverse("fields/{$form_name}");
     if ($field_node instanceof I2CE_MagicDataNode) {
         foreach ($field_node as $id => $fields) {
             if (!$fields instanceof I2CE_MagicDataNode) {
                 I2CE::raiseError("Invalid data stored in MagicData: {$migrate_path} fields/{$form_name}");
                 return false;
             }
             $obj = $factory->createContainer($form_name . '|' . $id, true);
             foreach ($field_list as $field => $map_form) {
                 $new_value = self::getMigratedValue($migrate_node, $form_name, $id, $field, $map_form);
                 if (is_array($new_value) && array_key_exists('old_value', $new_value) && !$new_value['old_value']) {
                     // No old value so nothing to do here.
                     continue;
                 }
                 if (is_array($new_value) && array_key_exists('new_value', $new_value) && $new_value['new_value']) {
                     $fieldObj = $obj->getField($field);
                     if (!$fieldObj instanceof I2CE_FormField) {
                         I2CE::raiseError("Failed to get new field for {$form_name}+{$field} ");
                         return false;
                     }
                     $fieldObj->setFromDB($new_value['new_value']);
                     $fieldObj->setStaticAttribute("DBEntry_change_type", I2CE_FormStorage_Mechanism::CHANGE_UPDATE);
                     if (!$storage->FF_save($fieldObj, false, $user)) {
                         I2CE::raiseError("Failed to save new field for {$form_name} {$field} " . $new_value['new_value']);
                         return false;
                     }
                 } else {
                     I2CE::raiseError("Migrate: Failed to get new value for {$id} {$map_form} {$field}");
                     return false;
                 }
             }
             $obj->cleanup();
             unset($obj);
             $field_node->{$id}->unpopulate(true, true);
         }
     }
     $migrate_node->unpopulate(true, true);
     return true;
 }
コード例 #17
0
 protected function import($file, $ignore_ids = false)
 {
     $reader = new XMLReader();
     $reader->open($file, null, 1 << 19);
     $save_ids = array();
     $count = 0;
     $exec = array('max_execution_time' => 20 * 60, 'memory_limit' => 256 * 1048576);
     $importer = new I2CE_FormRelationship_Importer();
     if (array_key_exists('HTTP_HOST', $_SERVER)) {
         $importer->setMessageCallback(array($this, 'pushMessage'));
     }
     $defaults = array('ignoreids' => $ignore_ids ? '1' : '0', 'nomatching' => '', 'invalid' => '');
     $next = false;
     while ($next || $reader->read()) {
         $next = false;
         if ($reader->nodeType != XMLReader::ELEMENT) {
             continue;
         }
         switch ($reader->name) {
             case 'relationshipCollection':
                 foreach ($defaults as $key => $val) {
                     if (($v = $reader->getAttribute($key)) !== null) {
                         $defaults[$key] = $v;
                     }
                 }
                 while ($reader->read()) {
                     //skip to a relationship sub-element
                     if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'relationship') {
                         break;
                     }
                 }
                 //break;  - purposefully do not break as we want to get process any relationship under a relationshipCollection
             //break;  - purposefully do not break as we want to get process any relationship under a relationshipCollection
             case 'relationship':
                 I2CE::longExecution($exec);
                 $node = $reader->expand();
                 $doc = new DOMDocument();
                 $i_node = $doc->importNode($node, true);
                 foreach ($defaults as $k => $v) {
                     $i_node->setAttribute($k, $v);
                 }
                 $new_ids = $importer->loadFromXML($i_node);
                 $save_ids = array_merge($save_ids, $new_ids);
                 if (array_key_exists('HTTP_HOST', $_SERVER) && count($new_ids) > 0) {
                     $this->pushMessage("Imported records with ids:\n" . implode(",", $new_ids));
                 }
                 $count++;
                 $reader->next();
                 $next = true;
                 break;
             default:
                 if (array_key_exists('HTTP_HOST', $_SERVER)) {
                     $this->pushError("Unrecognized data type: " . $reader->name);
                 }
                 break;
         }
     }
     $summary = "Import Summary:  (processed {$count} relationships)\n";
     foreach ($save_ids as $save_id => $msg) {
         $summary .= str_replace("\n", "\n  - ", $msg) . "\n";
     }
     I2CE::raiseMessage($summary);
     $this->pushMessage($summary);
     return true;
 }
コード例 #18
0
    $versions = array('i2ce' => $main_version, 'manage' => $main_version, 'common' => $main_version, 'qualify' => $main_version, 'textlayout' => $main_version);
    foreach ($versions as $pkg => $vers) {
        $versions[$pkg] = $vers . '-release';
        $packages[$pkg]['bzr'] = 'https://launchpad.net/' . $packages[$pkg]['pkg_name'];
        $packages[$pkg]['bzr_files'] = "http://bazaar.launchpad.net/~intrahealth+informatics/" . $packages[$pkg]['pkg_name'] . "/{$vers}-release/files/head:";
        $packages[$pkg]['bzr_annotate_files'] = "http://bazaar.launchpad.net/~intrahealth+informatics/" . $packages[$pkg]['pkg_name'] . "/{$vers}-release/annotate/head:";
        $packages[$pkg]['bzr_translate'] = "http://translations.launchpad.net/" . $packages[$pkg]['pkg_name'] . "/trunk/+pots/";
    }
}
/*************************************
 *
 *  processing of modules
 *
 *******************************************/
$found_modules = getAvailableModules();
I2CE::longExecution();
/***********************************************
 *
 *  go througgh each of the module and pull out the magic data nodes when/where they are defined.
 *
 ************************************/
function processConfigFile($module, $top_module, $file, &$md_nodes, &$child_nodes)
{
    global $packages, $module_packages;
    $mod_file = basename($file);
    $current_pkg = false;
    foreach ($packages as $pkg => $info) {
        if ($top_module == $info['top_module']) {
            $module_packages[$module] = $pkg;
            $current_pkg = $pkg;
            break;
コード例 #19
0
ファイル: I2CE_Util.php プロジェクト: apelon-ohie/ihris-site
 /**
  * Explode and execute a 
  * @param string $sql a nuch of sql queries
  * @param boolean $transact defaults to true meaning that the whole script is executed in a transaction.  If a string, it is the name of a savepoint to rollback to/release
  * @param MDB2 connection $db
  * @param string $delimiter.  Defaults to ';'. Needs to be exactly one character
  * @returns boolean true on sucess or false
  */
 public static function explodeAndExecuteSQLQueries($sql, $db, $transact = true, $delimiter = ';')
 {
     if (!is_string($sql)) {
         I2CE::raiseError("Invalid SQL script");
         return false;
     }
     I2CE::longExecution();
     if ($db->supports('transactions')) {
         if ($transact === true) {
             $db->beginTransaction();
             I2CE::raiseError("Beginning transaction");
         } else {
             if (is_string($transact)) {
                 if ($db->in_transaction) {
                     $db->query('SAVEPOINT $transact');
                 } else {
                     //we aren't in a transaction, so don't use the savepoint
                     $transact = true;
                     $db->beginTransaction();
                     I2CE::raiseError("Beginning transaction");
                 }
             }
         }
     }
     $len = strlen($sql);
     $in_string_single = false;
     $in_string_double = false;
     $in_string_back = false;
     $in_comment = false;
     $in_comment_ml = false;
     $beg_qry = 0;
     $t_qry = '';
     for ($i = 0; $i < $len; $i++) {
         switch ($sql[$i]) {
             case "\n":
                 if ($in_comment) {
                     $in_comment = false;
                     $beg_qry = $i + 1;
                     //beginning of query is next line
                 }
                 if ($in_comment || $in_comment_ml || $in_string_single !== false || $in_string_double || $in_string_back) {
                     continue;
                 }
                 if (preg_match('/^DELIMITER (.)$/', trim(substr($sql, $beg_qry, $i - $beg_qry)), $matches)) {
                     $delimiter = $matches[1];
                     $beg_qry = $i + 1;
                     //beginning of query is next line
                 }
                 continue;
             case "-":
                 if ($in_comment || $in_comment_ml || $in_string_single !== false || $in_string_double || $in_string_back) {
                     continue;
                 }
                 if ($i > 0 && $sql[$i - 1] == '-') {
                     $in_comment = true;
                     $t_qry .= $t_qry . trim(substr($sql, $beg_qry, $i - 1 - $beg_qry));
                     $beg_qry = -1;
                 }
                 break;
             case "#":
                 if ($in_comment || $in_comment_ml || $in_string_single !== false || $in_string_double || $in_string_back) {
                     continue;
                 }
                 $in_comment = true;
                 $t_qry .= $t_qry . trim(substr($sql, $beg_qry, $i - $beg_qry));
                 $beg_qry = $i + 1;
                 break;
             case '*':
                 if ($in_comment || $in_string_single !== false || $in_string_double || $in_string_back) {
                     continue;
                 }
                 if ($in_comment_ml) {
                     if ($i + 2 < $len && $sql[$i + 1] == '/') {
                         $in_comment_ml = false;
                         $beg_qry = $i + 2;
                     }
                 } else {
                     if ($i > 0 && $sql[$i - 1] == '/') {
                         $in_comment_ml = true;
                         $t_qry .= $t_qry . trim(substr($sql, $beg_qry, $i - 1 - $beg_qry));
                         $beg_qry = $i + 1;
                     }
                 }
                 continue;
                 break;
             case "`":
                 if ($in_comment || $in_comment_ml) {
                     continue;
                 }
                 if ($in_string_back) {
                     $in_escape_slash = false;
                     $in_escape_back = false;
                     if ($i > 0) {
                         if ($sql[$i - 1] == '\\') {
                             $in_escape_slash = true;
                             //can't have a \ apearing in a table or field name
                         }
                         $j = $i - 1;
                         while ($sql[$j] == '`') {
                             $in_escape_back = !$in_escape_back;
                             $j--;
                         }
                     }
                     if (!$in_escape_slash && !$in_escape_back) {
                         $in_string_back = false;
                     }
                 } else {
                     if ($in_string_single === FALSE && !$in_string_double) {
                         $in_string_back = true;
                     }
                 }
                 continue;
                 break;
             case '"':
                 if ($in_comment || $in_comment_ml) {
                     continue;
                 }
                 if ($in_string_double) {
                     $in_escape_slash = false;
                     $in_escape_double = false;
                     if ($i > 9) {
                         $j = $i - 1;
                         while ($sql[$j] == '\\') {
                             $in_escape_slash = !$in_escape_slash;
                             $j--;
                         }
                         $j = $i - 1;
                         while ($sql[$j] == '"') {
                             $in_escape_double = !$in_escape_double;
                             $j--;
                         }
                     }
                     if (!$in_escape_slash && !$in_escape_double) {
                         $in_string_double = false;
                     }
                 } else {
                     if ($in_string_single === false && !$in_string_back) {
                         $in_string_double = true;
                     }
                 }
                 continue;
                 break;
             case "'":
                 if ($in_comment || $in_comment_ml) {
                     continue;
                 }
                 if ($in_string_single !== false) {
                     $in_escape_slash = false;
                     if ($i > 0) {
                         $j = $i - 1;
                         while ($j > $in_string_single) {
                             if ($sql[$j] == '\\') {
                                 $in_escape_slash = !$in_escape_slash;
                                 $j--;
                             } else {
                                 break;
                             }
                         }
                     }
                     if (!$in_escape_slash) {
                         $in_string_single = false;
                     }
                 } else {
                     if (!$in_string_back && !$in_string_double) {
                         $in_string_single = $i;
                     }
                 }
                 continue;
                 break;
             case $delimiter:
                 if ($in_string_single !== false || $in_string_double || $in_string_back || $in_comment || $in_comment_ml) {
                     continue;
                 }
                 $qry = trim($t_qry . trim(substr($sql, $beg_qry, $i - $beg_qry)));
                 $beg_qry = $i + 1;
                 $t_qry = '';
                 if (!$qry) {
                     continue;
                 }
                 $result = $db->query($qry);
                 if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
                     if ($db->in_transaction) {
                         if ($transact === true) {
                             I2CE::raiseError("Rolling Back");
                             $db->rollback();
                         } else {
                             if (is_string($transact)) {
                                 I2CE::raiseError("Rolling Back to savepoint {$transact}");
                                 $db->query("ROLLBACK TO SAVEPOINT {$transact}");
                             }
                         }
                     }
                     if ($transact) {
                         I2CE::getConfig()->clearCache();
                     }
                     return false;
                 }
                 continue;
                 break;
             default:
                 break;
         }
     }
     //now make sure we pick up the last query
     $qry = trim($t_qry . trim(substr($sql, $beg_qry)));
     if ($qry) {
         $result = $db->query($qry);
         if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
             if ($db->in_transaction) {
                 if ($transact === true) {
                     I2CE::raiseError("Rolling Back");
                     $db->rollback();
                 } else {
                     if (is_string($transact)) {
                         I2CE::raiseError("Rolling Back to savepoint {$transact}");
                         $db->query("ROLLBACK TO SAVEPOINT {$transact}");
                     }
                 }
             }
             if ($transact) {
                 I2CE::getConfig()->clearCache();
             }
             return false;
         }
     }
     //we are done
     if ($db->in_transaction) {
         if ($transact === true) {
             I2CE::raiseError("Commiting");
             return $db->commit() == MDB2_OK;
         }
         if (is_string($transact)) {
             $db->query("RELEASE SAVEPOINT {$transact}");
             I2CE::raiseError("Released savepoint {$transact}");
         }
         return true;
     } else {
         return true;
     }
 }
コード例 #20
0
 protected static function _updateModules($updates, $removals = array(), $optional_excludes = array(), $disables = array())
 {
     I2CE::raiseError("Updating Modules");
     //make sure everything is nice and fresh
     clearstatcache();
     $mod_factory = I2CE_ModuleFactory::instance();
     $exec = array('max_execution_time' => 20 * 60, 'memory_limit' => 256 * 1048576);
     I2CE::longExecution($exec);
     if (!is_array($updates)) {
         $updates = array($updates);
     }
     if (!is_array($removals)) {
         $removals = array($removals);
     }
     $msg = "Will attempt to update:\n";
     foreach (array('Updates' => $updates, 'Removals' => $removals, 'Disables' => $disables) as $k => $v) {
         if (count($v) > 0) {
             $msg .= "\t{$k}:\n\t\t" . implode(',', $v) . "\n";
         }
     }
     I2CE::raiseError($msg);
     $storage = I2CE::getConfig();
     $tmp_storage = I2CE_MagicData::instance("temp_ModuleFactory");
     $configurator = new I2CE_Configurator($tmp_storage);
     if ($storage->setIfIsSet($sitemodule, "config/site/module")) {
         I2CE::raiseError("Site is set at " . $storage->getPath() . ' to be ' . $sitemodule);
         //make sure the site direcotry is added in to the config path.
         $data = $configurator->checkRequirements($updates, $disables, $removals, $mod_factory->getEnabled(), $sitemodule);
     } else {
         I2CE::raiseError("Site is not set at " . $storage->getPath());
         $data = $configurator->checkRequirements($updates, $disables, $removals, $mod_factory->getEnabled());
     }
     //note that checkRequirements has the result of putting _all_ valid config module metadata under /config/data of $tmp_storage
     if (isset($data['failure'])) {
         $storage->clearCache();
         I2CE::raiseError("Installation failed: " . $data['failure']);
         return false;
     }
     foreach (array_keys($data['removals']) as $shortname) {
         if (!$mod_factory->disable($shortname)) {
             $storage->clearCache();
             I2CE::raiseError("Unable to disable {$shortname}", E_USER_NOTICE);
             return false;
         }
     }
     //now we remove from the requirements list anything that is already enabled and  up-to-date
     if (count($data['moved']) > 0) {
         I2CE::raiseError("Found the following in another location.  Attempting to move:" . implode(',', array_keys($data['moved'])));
         I2CE::setupFileSearch(array(), true);
         //reset the file search and clear its cache
         I2CE::getFileSearch()->addPath('MODULES', dirname(dirname(__FILE__)), 'EVEN_HIGHER');
     }
     $skipped = array();
     $moved = array();
     foreach ($data['requirements'] as $shortname => $file) {
         if (!$mod_factory->isEnabled($shortname)) {
             continue;
         }
         if ($mod_factory->isUpToDate($shortname, $file) && $mod_factory->isUpToDateModule($shortname)) {
             //everything is in the correct place and up to date.
             $skipped[] = $shortname;
             $mod_factory->loadPaths($shortname, null, true);
             //for the loading of all categories for this module
             $storage->config->data->{$shortname}->file = $data['requirements'][$shortname];
             I2CE::raiseError("Updated {$shortname} config file to be " . $data['requirements'][$shortname]);
             unset($data['requirements'][$shortname]);
             //this module is enabled and the config is up-to-date so we dont need to do anything
             continue;
         }
         //let us see if this module has been moved
         if (!$storage->__isset("config/data/{$shortname}")) {
             continue;
         }
         if (!$tmp_storage->__isset("config/data/{$shortname}")) {
             continue;
         }
         $meta = $storage->config->data->{$shortname};
         $tmp_meta = $tmp_storage->config->data->{$shortname};
         foreach (array("hash", "last_access") as $key) {
             if (!isset($meta->{$key}) || !isset($tmp_meta->{$key}) || $tmp_meta->{$key} !== $meta->{$key}) {
                 continue 2;
             }
         }
         $class_file = null;
         $tmp_meta->setIfIsSet($class_file, "class/file");
         if ($class_file && ($class_file = I2CE_FileSearch::realPath($class_file))) {
             if (!$meta->__isset("class/hash")) {
                 continue;
             }
             if (!is_readable($class_file)) {
                 continue;
             }
             $contents = file_get_contents($class_file);
             if (!$contents) {
                 continue;
             }
             if ($meta->class->hash !== md5($contents)) {
                 continue;
             }
         }
         $mtimes = array();
         foreach (array("class/file", "file") as $f) {
             if (!isset($tmp_meta->{$f})) {
                 continue;
             }
             @($mtimes[$f] = filemtime(I2CE_FileSearch::realPath($tmp_meta->{$f})));
             if (!$mtimes[$f]) {
                 continue 2;
             }
         }
         if (false == $mod_factory->checkLocalesUpToDate($shortname, $class_file)) {
             //the locales for this module are not up to date
             continue;
         }
         //we made it here.  we can skip the update.
         I2CE::raiseError("Able to move config file for {$shortname} from:\n  " . $meta->file . "\nto:\n  " . $tmp_meta->file);
         foreach (array("class/file" => "class/last_access", "file" => "last_access") as $f => $a) {
             $val = null;
             $tmp_meta->setIfIsSet($val, $f);
             if ($val === null) {
                 continue;
             }
             $meta->{$f} = $val;
             $meta->{$a} = $mtimes[$f];
             $tmp_meta->{$a} = $mtimes[$f];
         }
         unset($data['requirements'][$shortname]);
         //this module is enabled and the config is up-to-date so we dont need to do anything
         $mod_factory->loadPaths($shortname, null, true);
         //for the loading of all categories for this module
         $moved[] = $shortname;
     }
     if (count($skipped) > 0) {
         I2CE::raiseError("Skipping update on the following up-to-date modules:" . implode(',', $skipped));
     }
     if (count($moved) > 0) {
         I2CE::raiseError("Moved the following  modules:" . implode(',', $moved));
     }
     I2CE::raiseError("Attempting to update/enable the following out of date modules: " . implode(',', array_keys($data['requirements'])));
     //make sure all of our class paths for existing moduels are loaded.
     $good_modules = array_diff($mod_factory->getEnabled(), $data['removals'], array_keys($data['requirements']));
     I2CE::raiseError("The following modules class paths are being added:\n\t" . implode(',', $good_modules));
     $mod_factory->loadPaths($good_modules, 'CLASSES', true);
     if (!array_key_exists('optional', $data) || !is_array($data['optional'])) {
         $data['optional'] = array();
     }
     if (is_string($optional_excludes)) {
         $optional_excludes = array($optional_excludes);
     }
     if (!is_array($optional_excludes)) {
         $optional_excludes = array();
     }
     $to_enable = array_merge($data['requirements'], $data['optional']);
     //while (count ($data['requirements']) > 0) {
     I2CE::raiseError("Trying to enable the following required:\n" . implode(" ", array_keys($data['requirements'])));
     I2CE::raiseError("Trying to enable the following optional:\n" . implode(" ", array_keys($data['optional'])));
     I2CE::raiseError("Trying to enable the following:\n" . implode(" ", array_keys($to_enable)));
     while (count($to_enable) > 0) {
         $shortname = key($to_enable);
         // reset ($data['requirements']);
         // $shortname = key($data['requirements']);
         if (!is_string($shortname) || strlen($shortname) == 0) {
             I2CE::raiseError("Invalid Shortname");
             continue;
         }
         $file = array_shift($to_enable);
         if (array_key_exists($shortname, $data['optional']) && in_array($shortname, $optional_excludes)) {
             continue;
         }
         $old_vers = '0';
         $storage->setIfIsSet($old_vers, "/config/data/{$shortname}/version");
         $new_vers = null;
         $tmp_storage->setIfIsSet($new_vers, "/config/data/{$shortname}/version");
         $mod_config = $tmp_storage->config->data->{$shortname};
         $storage->__unset("/config/data/{$shortname}");
         //set the module's metadata to the new stuff.
         $storage->config->data->{$shortname} = $mod_config;
         //keep the old version set around until we know that the module was upgraded
         $storage->config->data->{$shortname}->version = $old_vers;
         if (!$tmp_storage->__isset("/config/data/{$shortname}/class/name")) {
             //there is no class associated in the new version of  this module.
             if ($storage->__isset("/config/data/{$shortname}/class/name")) {
                 //there was a class previously assoicated to this module -- remove its hooks/fuzzy methods,
                 $mod_factory->removeHooks($shortname);
                 unset($storage->config->data->{$shortname}->class);
             }
         }
         foreach (array('conflict' => 'conflict_external', 'requirement' => 'requirement_external') as $type => $key) {
             if ($mod_config->is_parent($key)) {
                 foreach ($mod_config->{$key} as $ext => $req_data) {
                     if ($req_data instanceof I2CE_MagicDataNode) {
                         $req_data = $req_data->getAsArray();
                     } else {
                         $req_data = array();
                     }
                     foreach ($req_data as $req_d) {
                         if (!is_array($req_d) || !array_key_exists('eval', $req_d) || !$req_d['eval']) {
                             continue;
                         }
                         $eval = null;
                         @eval('$eval = ' . $req_d['eval'] . ';');
                         if (is_bool($eval) && !$eval) {
                             if (self::failedRequiredUpdate($shortname, $data, "Could not verify external {$type} {$ext} for {$shortname}", $configurator)) {
                                 return false;
                             } else {
                                 continue 4;
                             }
                         }
                     }
                 }
             }
         }
         $mod_storage = I2CE_MagicData::instance("temp_ModuleFactory_" . $shortname);
         I2CE::getFileSearch()->addPath('MODULES', dirname(dirname(__FILE__)), 'EVEN_HIGHER');
         $r_file = I2CE_FileSearch::realPath($file);
         $mod_configurator = new I2CE_Configurator($mod_storage);
         $s = $mod_configurator->processConfigFile($r_file, false, true, true, false);
         if (!is_string($s)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could load configuration file", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if ($s != $shortname) {
             //be super safe
             if (self::failedRequiredUpdate($shortname, $data, "Configuration shortname mismatch ({$s}/{$shortname})", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         self::processErasers($mod_config, $old_vers);
         $loaded = self::loadModuleMagicData($shortname, $r_file, $old_vers, $new_vers, $mod_configurator);
         if ($loaded === false) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not load magic data", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         $loaded_mod_config = $mod_storage->config->data->{$shortname};
         self::processErasers($loaded_mod_config, $old_vers);
         if (!self::preUpgradeModule($shortname, $old_vers, $new_vers, $mod_storage)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not pre-update module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         //if $loaded === true, then there was no magic data to update, so we can skip the store.
         if (is_array($loaded) && !self::storeModuleMagicData($shortname, $old_vers, $new_vers, $mod_configurator, $loaded)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not store magic data", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if (!self::upgradeModule($shortname, $old_vers, $new_vers)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not upgrade module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         if (!self::postUpdateModule($shortname, $old_vers, $new_vers)) {
             if (self::failedRequiredUpdate($shortname, $data, "Could not post update module", $configurator)) {
                 return false;
             } else {
                 continue;
             }
         }
         $mod_factory->setModuleHash($shortname);
         $mod_factory->setModuleClassHash($shortname, false);
         $mod_configurator->__destruct();
         $mod_configurator = null;
         $mod_storage->erase();
         $mod_storage = null;
         $storage = I2CE::getConfig();
         //just to make sure that any upgrades did not change the storage.  this happens with i2ce install for example
         $storage->config->data->{$shortname}->version = $new_vers;
         //we updated this module.  update the permanent modules config data with the temporary
         $mod_factory->loadPaths($shortname, null, true);
         //for the loading of all categories for this module
     }
     I2CE::raiseError("Enabled Modules: " . implode(',', $mod_factory->getEnabled()));
     return true;
 }
コード例 #21
0
 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);
 }
コード例 #22
0
    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();
    }
コード例 #23
0
 protected function process_saves($queue, $allowed_duplicates, $allowed_invalid)
 {
     $this->raiseError("Processing " . count($queue) . " forms");
     $save_ids = array();
     $this->raiseError("BEGIN QUEUE PROCESSING");
     $exec = array('max_execution_time' => 20 * 60, 'memory_limit' => 256 * 1048576);
     foreach ($queue as $queue_entry) {
         I2CE::longExecution($exec);
         if (!is_array($queue_entry) || !($join_style = $queue_entry['join_style']) || !($form_obj = $queue_entry['form_obj']) instanceof I2CE_Form) {
             $this->raiseError("Skipping invalid queue entry");
             continue;
         }
         $msg = "imported new record";
         $relparent_form_obj = $queue_entry['relparent_form_obj'];
         $join_field = $queue_entry['join_field'];
         $do_save = $queue_entry['do_save'];
         $form = $form_obj->getName();
         $matched_obj = false;
         if ($form_obj instanceof I2CE_List && $join_style == 'parent_field' && !in_array($form, $allowed_duplicates) && count($unique_fields = $this->get_unique_fields($form_obj)) > 0) {
             $matched_obj = $this->find_matching($form_obj);
             if ($matched_obj instanceof I2CE_Form) {
             }
         }
         switch ($join_style) {
             case 'primary_form':
                 $msg .= ' - primary_form';
                 //do nothing special
                 break;
             case 'child':
                 if ($relparent_form_obj instanceof I2CE_Form) {
                     $form_obj->setParent($relparent_form_obj);
                     $msg .= ' - child of ' . $relparent_form_obj->getNameId();
                 }
                 //need to specify that we need to use the relationship parent  form node's  object that was just saved
                 //to get the id.
                 break;
             case 'parent_field':
                 //This is a join that you would do if $join_node corresponded to a position form and had person_position in the parent form node of the relationship
                 //in this case, you want the $position_obj to save before the $person_position_obj so that you can
                 //set $person_position_obj to have the parent id created for $position_obj
                 if (!$matched_obj instanceof I2CE_Form) {
                     break;
                 }
                 $nameid = $matched_obj->getNameID();
                 if (!$relparent_form_obj instanceof I2CE_Form || !$join_field || !($join_field_obj = $relparent_form_obj->getField($join_field)) instanceof I2CE_FormField_MAP) {
                     break;
                 }
                 $msg .= " - joined from {$join_field} of " . $relparent_form_obj->getNameId();
                 $join_field_obj->setFromDB($nameid);
                 //Note the join_field_obj is after the current queue entry on the list.  this means it will be saved later in the loop
                 break;
             default:
                 $this->raiseError("Join style {$join_style} is not supported");
                 break;
         }
         if (!$matched_obj instanceof I2CE_Form) {
             //save a new form
             $this->raiseError("Form instance not found, validating. (" . $form_obj->getNameID() . ")");
             if (!in_array($form, $allowed_invalid)) {
                 $form_obj->validate();
             }
             if ($form_obj->hasInvalid()) {
                 $this->raiseError("Form instance invalid. (" . $form_obj->getNameID() . ")\n<pre>" . htmlspecialchars($form_obj->getXMLRepresentation(false)) . "</pre>");
                 $msgs = array();
                 foreach ($form_obj as $field_name => $field_obj) {
                     if (!$field_obj->hasInvalid()) {
                         continue;
                     }
                     $t_msg = $field_obj->getInvalid();
                     if (is_string($t_msg)) {
                         $t_msg .= "\nValue = " . $field_obj->getDBValue();
                         $msgs[] = " [" . $field_obj->getName() . "] " . $t_msg;
                     } else {
                         if (is_array($t_msg)) {
                             foreach ($t_msg as $i => $tt_msg) {
                                 if (is_string($tt_msg)) {
                                     continue;
                                 }
                                 unset($t_msg[$i]);
                             }
                             $msgs[] = "  [" . $field_obj->name() . "]" . implode(",", $t_msg) . "\nValue = " . $field_obj->getDBValue();
                         }
                     }
                 }
                 $md5 = md5($form_obj->getXMLRepresentation(false));
                 $msg = "Invalid form. will not attempt save. (" . $form_obj->getNameID() . ")\n" . implode("\n", $msgs);
                 $this->raiseError($msg);
                 $save_ids[$md5] = $msg;
             } else {
                 if ($relparent_form_obj instanceof I2CE_Form && $relparent_form_obj->getID() == '0' && $join_style == 'child') {
                     $md5 = md5($form_obj->getXMLRepresentation(false));
                     $msg = "related form (" . $relparent_form_obj->getNameID() . ") is unsaved so will not attempt save (" . $form_obj->getNameID() . ") ";
                     $this->raiseError($msg);
                     $save_ids[$md5] = $msg;
                 } else {
                     if ($do_save) {
                         if (!$form_obj->save($this->user)) {
                             $md5 = md5($form_obj->getXMLRepresentation());
                             $msg = "Could not save " . $form_obj->getNameID();
                             $this->raiseError($msg);
                             $save_ids[$md5] = $msg;
                         } else {
                             $nameid = $form_obj->getNameID();
                             $this->raiseError("Saved {$nameid}");
                             if ($queue_entry['relationship'] && $queue_entry['hash'] && $join_style == 'primary_form') {
                                 self::markProcessed($nameid, $queue_entry['relationship'], $queue_entry['hash']);
                             }
                             $save_ids[$nameid] = $msg;
                             if ($join_style == 'parent_field') {
                                 if (!$relparent_form_obj instanceof I2CE_Form || !$join_field || !($join_field_obj = $relparent_form_obj->getField($join_field)) instanceof I2CE_FormField_MAP) {
                                     break;
                                 }
                                 $msg .= " - joined from {$join_field} of " . $relparent_form_obj->getNameId();
                                 $join_field_obj->setFromDB($nameid);
                                 //Note the join_field_obj is after the current queue entry on the list.  this means it will be saved later in the loop
                             }
                         }
                     }
                 }
             }
         }
     }
     return $save_ids;
 }
コード例 #24
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;
         }
     }
 }