/**
  * Check for duplicates and save the user alert
  * @param I2CE_User $user
  * @param boolean $transact
  * @return boolean
  */
 public function save($user, $transact = true)
 {
     if ($this->getId() === '0') {
         $find_duplicates = array('operator' => 'AND', 'operand' => array(array('operator' => 'FIELD_LIMIT', 'field' => 'message', 'style' => 'lowerequals', 'data' => array('value' => strtolower($this->message))), array('operator' => 'FIELD_LIMIT', 'field' => 'time_ack', 'style' => 'null'), array('operator' => 'FIELD_LIMIT', 'field' => 'alert_type', 'style' => 'equals', 'data' => array('value' => $this->alert_type))));
         if ($this->link == '') {
             $find_duplicates['operand'][] = array('operator' => 'FIELD_LIMIT', 'field' => 'link', 'style' => 'null');
         } else {
             $find_duplicates['operand'][] = array('operator' => 'FIELD_LIMIT', 'field' => 'link', 'style' => 'equals', 'data' => array('value' => $this->link));
         }
         if ($this->link_text == '') {
             $find_duplicates['operand'][] = array('operator' => 'FIELD_LIMIT', 'field' => 'link_text', 'style' => 'null');
         } else {
             $find_duplicates['operand'][] = array('operator' => 'FIELD_LIMIT', 'field' => 'link_text', 'style' => 'lowerequals', 'data' => array('value' => strtolower($this->link_text)));
         }
         $found = I2CE_FormStorage::search('user_alert', $this->getParent(), $find_duplicates, array("-time_sent"), 1);
         if ($found) {
             I2CE::raiseMessage("found duplicates so increasing repeats. {$found}");
             $duplicate = I2CE_FormFactory::instance()->createContainer("user_alert|" . $found);
             $duplicate->populate();
             $duplicate->repeated++;
             return $duplicate->save($user, $transact);
         }
     }
     return parent::save($user, $transact);
 }
 protected function _generateCache()
 {
     if (!($last_tmp_table = $this->setupQueries())) {
         I2CE::raiseError("Could not process form tree for report {$this->report}");
         return false;
     }
     $counter = count($this->populate_queries);
     $md5_key = 'no_md5';
     foreach ($this->populate_queries[$counter] as &$query) {
         if (is_array($query)) {
             $query = $query[$md5_key];
         }
     }
     unset($query);
     if (array_key_exists('update_set_md5', $this->populate_queries[$counter])) {
         unset($this->populate_queries[$counter]['update_set_md5']);
     }
     $replace = false;
     while ($counter && array_key_exists($counter, $this->populate_queries)) {
         if ($counter > 1) {
             $md5_key = 'no_md5';
             if (array_key_exists('insert_limit', $this->populate_queries[$counter]) || array_key_exists('insert_nolimit', $this->populate_queries[$counter])) {
                 $md5_key = 'md5';
             } else {
                 if (array_key_exists('update_set_md5', $this->populate_queries[$counter - 1])) {
                     unset($this->populate_queries[$counter - 1]['update_set_md5']);
                 }
             }
             foreach ($this->populate_queries[$counter - 1] as &$query) {
                 if (is_array($query)) {
                     $query = $query[$md5_key];
                 }
             }
             unset($query);
             if (array_key_exists('update', $this->populate_queries[$counter])) {
                 $this->populate_queries[$counter - 1]['create'] = $this->populate_queries[$counter]['create'];
                 $this->populate_queries[$counter - 1]['drop'] = $this->populate_queries[$counter]['drop'];
                 //$this->populate_queries[$counter-1]['drop_prev'] = $this->populate_queries[$counter]['drop_prev'];
                 unset($this->populate_queries[$counter]['create']);
                 unset($this->populate_queries[$counter]['drop']);
                 unset($this->populate_queries[$counter]['insert_copy']);
                 //unset( $this->populate_queries[$counter]['drop_prev'] );
                 if (!$replace) {
                     $replace = '[' . $counter . ']`';
                 }
                 $find = '[' . ($counter - 1) . ']`';
                 foreach ($this->populate_queries[$counter - 1] as $type => &$query) {
                     if ($type != 'drop_prev') {
                         $query = str_replace($find, $replace, $query);
                     }
                 }
                 unset($query);
             } else {
                 $replace = false;
             }
         }
         $counter--;
     }
     foreach ($this->populate_queries as $qry_list) {
         foreach ($qry_list as $type => $qry) {
             /*
             if ( $type == 'drop_prev' ) {
                 I2CE::raiseMessage( "Skipping $qry" );
                 continue;
             }
             */
             I2CE::raiseError("Doing {$type}: {$qry}");
             $start_time = time();
             $res = $this->db->exec($qry);
             $end_time = time();
             if (I2CE::pearError($res, "Unable to populate cached report")) {
                 return false;
             }
             if (substr(ltrim($qry), 0, 6) == 'INSERT' || substr(ltrim($qry), 0, 6) == 'UPDATE') {
                 I2CE::raiseMessage("Inserted {$res} rows");
             }
             I2CE::raiseMessage("Query took " . ($end_time - $start_time) . " seconds.");
         }
     }
     // we move over the tmp_table to table.
     if (!$this->dropTable(false)) {
         return false;
     }
     if (I2CE::pearError($this->db->exec("RENAME TABLE {$last_tmp_table} TO {$this->table}"), "Could not rename temp table")) {
         return false;
     }
     return true;
 }
 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;
 }
 /**
  * read the entire row and parse for data
  * @param string $row. If not an excel worksheet row, issue a message and return false
  * @returns array
  */
 protected function _readRow($row)
 {
     if (!$row instanceof PHPExcel_Worksheet_Row) {
         I2CE::raiseMessage("Invalid row object" . get_class($row));
         return false;
     }
     $cellIterator = $row->getCellIterator();
     $cellIterator->setIterateOnlyExistingCells(false);
     $data = array();
     foreach ($cellIterator as $cell) {
         $data[] = $cell->getValue();
     }
     return $data;
 }
 /**
  * Perform the main actions of the page.
  * @return boolean
  */
 protected function action()
 {
     if (!parent::action()) {
         return false;
     }
     if (!$this->hasPermission("role(admin)")) {
         $this->userMessage("You do not have permission to view this page.");
         return false;
     }
     $pos_mech = I2CE_FormStorage::getStorageMechanism("position");
     $pers_pos_mech = I2CE_FormStorage::getStorageMechanism("person_position");
     if (!$pos_mech instanceof I2CE_FormStorage_entry || !$pers_pos_mech instanceof I2CE_FormStorage_entry) {
         I2CE::raiseMessage("Invalid storage type for position and person position forms. " . get_class($pos_mech) . get_class($pers_pos_mech));
         $this->template->addFile("mass_delete_by_search_error_invalid.html");
         return true;
     }
     $people = $this->post('people');
     if (!is_array($people) || count($people) < 1) {
         $this->template->addFile("mass_delete_by_search_empty.html");
     } else {
         $step = 'choose';
         if ($this->post_exists('step')) {
             $step = $this->post('step');
         }
         if ($step == "delete") {
             if ($this->post('yes') != 'yes') {
                 $this->template->appendFileById("mass_delete_by_search_error_yes.html", "p", "error");
                 $step = "confirm";
             }
             $userAccess = new I2CE_UserAccess_Mechanism();
             if (!$this->post_exists('admin_pass') || !$userAccess->userHasPassword('i2ce_admin', $this->post('admin_pass'))) {
                 $this->template->appendFileById("mass_delete_by_search_error_password.html", "p", "error");
                 $step = "confirm";
             }
         }
         switch ($step) {
             case "choose":
                 $this->template->addFile("mass_delete_by_search_form.html");
                 $msgNode = $this->template->addFile("mass_delete_by_search_confirm_message.html");
                 foreach ($people as $person) {
                     $persObj = I2CE_FormFactory::instance()->createContainer($person);
                     $persObj->populate();
                     $persNode = $this->template->appendFileById("mass_delete_by_search_each.html", "li", "search_list");
                     $this->template->setDisplayDataImmediate("people[]", array('value' => $person, 'id' => "check_{$person}"), $persNode);
                     $this->template->setDisplayDataImmediate("person_name", $persObj->surname . ', ' . $persObj->firstname, $persNode);
                     $label = $this->template->query("label[@name='search_label']", $persNode);
                     if ($label->length == 1) {
                         $label->item(0)->setAttribute("for", "check_{$person}");
                     }
                 }
                 break;
             case "confirm":
                 $list = $this->getDeleteList($people);
                 if ($list === null) {
                     $this->template->addFile("mass_delete_by_search_error_notfound.html");
                 } elseif (count($list) < 1) {
                     I2CE::raiseMessage("Invalid return data from getDeleteList!");
                     $this->template->addFile("mass_delete_by_search_error_unkonwn.html");
                 } else {
                     $formNode = $this->template->addFile("mass_delete_by_search_form.html");
                     $this->template->setDisplayDataImmediate("step", "delete");
                     $addNode = $this->template->addFile("mass_delete_by_search_authenticate_form.html");
                     $would_delete = I2CE_FormStorage_entry::massDelete($list, array());
                     $msgNode = $this->template->addFile("mass_delete_by_search_delete_count.html");
                     $this->template->setDisplayDataImmediate("delete_count", $would_delete, $msgNode);
                     foreach ($people as $person) {
                         $persObj = I2CE_FormFactory::instance()->createContainer($person);
                         $persObj->populate();
                         $persNode = $this->template->appendFileById("mass_delete_by_search_each_final.html", "li", "search_list");
                         $this->template->setDisplayDataImmediate("people[]", $person, $persNode);
                         $this->template->setDisplayDataImmediate("person_name", $persObj->surname . ', ' . $persObj->firstname, $persNode);
                     }
                 }
                 break;
             case "delete":
                 $list = $this->getDeleteList($people);
                 if ($list === null) {
                     $this->template->addFile("mass_delete_by_search_error_notfound.html");
                 } elseif (count($list) < 1) {
                     I2CE::raiseMessage("Invalid return data from getDeleteList!");
                     $this->template->addFile("mass_delete_by_search_error_unkonwn.html");
                 } else {
                     $formNode = $this->template->addFile("mass_delete_by_search_form.html");
                     $this->template->setDisplayDataImmediate("step", "delete");
                     $addNode = $this->template->addFile("mass_delete_by_search_authenticate_form.html");
                     I2CE_ModuleFactory::callHooks("pre_mass_delete_person", $people, $this->post());
                     if (($deleted = I2CE_FormStorage_entry::massDelete($list, array(), false)) !== false) {
                         $node = $this->template->addFile("mass_delete_by_search_success.html");
                         $this->template->setDisplayDataImmediate("delete_count", $deleted, $node);
                         if (I2CE_ModuleFactory::instance()->isEnabled("CachedForms")) {
                             $forms = I2CE_FormFactory::instance()->getNames();
                             $success = array();
                             $failure = array();
                             foreach ($forms as $form) {
                                 try {
                                     $cachedForm = new I2CE_CachedForm($form);
                                 } catch (Exception $e) {
                                     $success[] = $form;
                                     continue;
                                 }
                                 if (!$cachedForm->dropTable()) {
                                     $failure[] = $form;
                                 }
                             }
                             if (count($failure) > 0) {
                                 $this->template->addFile("mass_delete_by_search_cache_fail.html", "p");
                             } else {
                                 $this->template->addFile("mass_delete_by_search_cache_success.html", "p");
                             }
                         }
                     } else {
                         I2CE::raiseError("An error occurred trying to mass delete by search.");
                         $this->template->addFile("mass_delete_by_search_error_unkonwn.html");
                     }
                 }
                 break;
         }
     }
 }
 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);
 }
 /**
  * Perform the action for this page.
  */
 protected function action()
 {
     if ($this->get_exists('delete') && $this->get('delete') == 1) {
         $parent_id = $this->getPrimary()->getParent();
         $form_id = $this->getPrimary()->getNameId();
         $child_forms = $this->getPrimary()->getChildForms();
         if (count($child_forms) > 0) {
             I2CE::raiseMessage("Tried to delete a child form {$form_id} when there are possible child forms.");
             $message = "This form can not be deleted.";
             I2CE::getConfig()->setIfIsSet($message, "/modules/forms/page_feedback_messages/person_child_delete_not_allowed");
         } else {
             $allowable = false;
             I2CE::getConfig()->setIfIsSet($allowable, "/modules/Person/deleteable_children/" . $this->form_name);
             I2CE::raiseMessage("deleting {$form_id} under {$parent_id} requested by user " . $this->getUser()->getId());
             if ($allowable) {
                 if ($this->checkActionPermission('delete')) {
                     if ($this->getPrimary()->delete()) {
                         $message = "The requested form has been deleted.";
                         I2CE::getConfig()->setIfIsSet($message, "/modules/forms/page_feedback_messages/person_child_delete_success");
                     } else {
                         $message = "An error occurred deleting this form.";
                         I2CE::getConfig()->setIfIsSet($message, "/modules/forms/page_feedback_messages/person_child_delete_fail");
                     }
                 } else {
                     $message = "You do not have permission to delete this form.";
                     I2CE::getConfig()->setIfIsSet($message, "/modules/forms/page_feedback_messages/person_child_delete_not_permitted");
                 }
             } else {
                 $message = "This form can not be deleted.";
                 I2CE::getConfig()->setIfIsSet($message, "/modules/forms/page_feedback_messages/person_child_delete_not_allowed");
             }
         }
         $this->userMessage($message);
         $this->setRedirect("view?id=" . $parent_id);
         return true;
     }
     return parent::action();
 }
 protected function loadHTMLTemplates()
 {
     parent::loadHTMLTemplates();
     /* need to set new_person_position and then person here to make sure defaults are OK.
        Otherwise need form_person_base.html and button_confirm.html to be different */
     $this->template->setForm($this->new_person_position);
     $this->template->setForm($this->person);
     $forms = array('current_person_position' => $this->new_person_position, 'current_person_position' => $this->current_person_position, 'new_position' => $this->new_position, 'current_position' => $this->current_position, 'new_salary' => $this->new_salary, 'current_salary' => $this->current_salary);
     foreach ($forms as $class => $form) {
         if (!$form instanceof I2CE_Form) {
             I2CE::raiseMessage("{$class} isn't available");
             continue;
         }
         foreach ($this->template->query("//*[@class='form:{$class}']") as $node) {
             $this->template->setForm($form, $node);
         }
     }
     foreach (array('id', 'parent') as $key) {
         if ($this->request_exists($key) && $this->request($key)) {
             $this->template->setDisplayData($key, $this->request($key));
         }
     }
 }
 /**
  * Hooked Function to check if a field is unique or unique restricted to a certain field
  * @param I2CE_FormField $field_obj
  * @returns boolean
  */
 public function validate_formfield($field_obj)
 {
     if (!$field_obj->hasOption('unique') || !$field_obj->getOption('unique') || !$field_obj->isValid() || !$field_obj->issetValue() || $field_obj->getDBValue() == "") {
         return;
     }
     $where = array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => $field_obj->getName(), 'data' => array('value' => $field_obj->getDBValue()));
     $form_obj = $field_obj->getContainer();
     if (!$form_obj instanceof I2CE_Form) {
         I2CE::raiseError(get_class($form_obj));
         return;
     }
     $names = array();
     $search_parent = false;
     if ($field_obj->hasOption('unique_field')) {
         $unique = $field_obj->getOption('unique_field');
         if (strpos($unique, ':') !== false) {
             //the value is a mapped thing.  this is handled by hooked mehtod defined in I2CE_Module_List
             return;
         }
         $unique_fields = explode(',', $unique);
         $unique_where = array($where);
         foreach ($unique_fields as $unique_field) {
             if ($unique_field == "parent") {
                 $search_parent = $form_obj->getParent();
                 if ($search_parent == "") {
                     // If there is no parent then we can't validate
                     // by parent so ignore this
                     return;
                 }
                 continue;
             }
             if (!($unique_field_obj = $form_obj->getField($unique_field)) instanceof I2CE_FormField) {
                 I2CE::raiseError("Invalid field {$unique_field}");
                 return;
             }
             if ($unique_field_obj->hasHeader('default')) {
                 $names[] = $unique_field_obj->getHeader('default');
             } else {
                 $names[] = $unique_field_obj->getName();
             }
             if ($unique_field_obj->isValid()) {
                 $unique_where[] = array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => $unique_field_obj->getName(), 'data' => array('value' => $unique_field_obj->getDBValue()));
             } else {
                 $unique_where[] = array('operator' => 'OR', 'operand' => array(0 => array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => $unique_field_obj->getName(), 'data' => array('value' => $unique_field_obj->getDBValue())), 1 => array('operator' => 'FIELD_LIMIT', 'style' => 'null', 'field' => $unique_field_obj->getName())));
             }
         }
         if (count($unique_where) > 1) {
             //we added somehitng
             $where = array('operator' => 'AND', 'operand' => $unique_where);
         }
     }
     $found = I2CE_FormStorage::search($form_obj->getName(), $search_parent, $where, array(), 1);
     if ($found !== false && '' . $found != '' . $form_obj->getId()) {
         I2CE::raiseMessage("found is {$found} and id is " . $form_obj->getId() . " and names are " . print_r($names, true));
         if (count($names) > 1) {
             $field_obj->setInvalidMessage('unique_fields', null, ' ' . implode(', ', $names));
             //$field_obj->setInvalid("This must be unique and another record has this value for the given value of the fields " .implode(',',$names) );
         } else {
             if (count($names) == 1) {
                 $field_obj->setInvalidMessage('unique_field', null, ' ' . implode(', ', $names));
                 //$field_obj->setInvalid("This must be unique and another record has this value for the given value of the field " .implode(',',$names) );
             } else {
                 $field_obj->setInvalidMessage('unique');
                 //$field_obj->setInvalid("This must be unique and another record has this value." );
             }
         }
     }
 }
 public static function set_uuid_on_form($form, $field = 'csd_uuid')
 {
     if (!$form instanceof I2CE_Form) {
         I2CE::raiseError("Bad form");
         return;
     }
     if ($form->getID() == '0' || $form->getID() == '') {
         return;
     }
     if (!($field_obj = $form->getField($field)) instanceof I2CE_FormField) {
         I2CE::raiseError("{$field} does not exist on " . $form->getNameID());
         return;
     }
     if (!($field_obj->getDBValue() == '')) {
         return;
     }
     if ($id = self::generate_uuid($form)) {
         I2CE::raiseMessage("Setting csd uuid for " . $form->getNameID());
         $field_obj->setFromDB($id);
     }
 }
 /**
  * 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'];
     }
     I2CE::raiseMessage($style);
     $this->cols = array_keys($headers);
     switch ($style) {
         case 'xml':
             $post = " </reportData>\n</ihrisReport>\n";
             array_shift($this->cols);
             $pre = $this->getXMLMetaData($headers);
             break;
         case 'xls_2004_xml':
             $post = "  </Table>\n  <WorksheetOptions xmlns='urn:schemas-microsoft-com:office:excel'>\n   <PageLayoutZoom>0</PageLayoutZoom>\n   <Selected/>\n   <Panes>\n    <Pane>\n     <Number>3</Number>\n     <ActiveRow>1</ActiveRow>\n    </Pane>\n   </Panes>\n   <ProtectObjects>False</ProtectObjects>\n   <ProtectScenarios>False</ProtectScenarios>\n  </WorksheetOptions>\n </Worksheet>\n</Workbook>\n";
             $pre = $this->get_XLS_2004_XML_MetaData($headers);
             break;
         case 'tab':
             $post = '';
             $pre = "" . $this->processResultRowArray($headers);
             break;
         case 'csvxls':
             $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;
 }
 /**
  * Return the entry history for this person as an array
  * @param integer $userid The user id
  * @param string $username The user name
  * @param integer $days The number of days to include
  * @return array
  */
 protected static function setupEntryHistory($userid, $username, $days = 5)
 {
     if (!is_array(self::$entries)) {
         self::$entries = array();
     }
     if (array_key_exists($userid, self::$entries)) {
         return self::$entries[$userid];
     } else {
         self::$entries[$userid] = array('has_person' => false, 'has_forms' => false, 'dates' => array());
         if (!self::setupDB()) {
             return false;
         }
         $result = self::$prepared['entry_history']->execute(array($username, $days - 1, $username, $username));
         if (I2CE::pearError($result, "Error getting entry history: ")) {
             unset(self::$entries[$userid]);
             return false;
         }
         $records = array();
         $tally = array();
         $forms = array();
         $person = array();
         $parents = array();
         while ($row = $result->fetchRow()) {
             $tally[$row->date][] = $row->record;
             $records[$row->record] = 1;
             $forms[$row->record] = $row->form;
             if ($row->parent_id == '0|0') {
                 continue;
             }
             list($pform, $pid) = explode('|', $row->parent_id);
             if ($pform == 'person') {
                 $person[$row->record] = $pid;
             } else {
                 if (!array_key_exists($pid, $parents)) {
                     $parents[$pid] = array();
                 }
                 $parents[$pid][] = $row->record;
             }
         }
         $result->free();
         if (count($records) == 0) {
             return true;
         }
         $loop_check = 0;
         while (count($parents) > 0) {
             if ($loop_check++ > 50) {
                 I2CE::raiseError("Too many loops for the entry history for {$userid} ({$days} days)");
                 return false;
             }
             $parent_query = "SELECT id,parent_form,parent_id FROM record WHERE id IN ( " . implode(',', array_keys($parents)) . " )";
             $result = self::$db->query($parent_query);
             if ($result->numRows() == 0) {
                 $parents = array();
             } else {
                 while ($row = $result->fetchRow()) {
                     if (!$row->parent_form || !$row->parent_id) {
                         unset($parents[$row->id]);
                         continue;
                     }
                     if ($row->parent_form == 'person') {
                         foreach ($parents[$row->id] as $record) {
                             $person[$record] = $row->parent_id;
                         }
                         unset($parents[$row->id]);
                     } else {
                         if (!array_key_exists($row->parent_id, $parents)) {
                             $parents[$row->parent_id] = array();
                         }
                         foreach ($parents[$row->id] as $record) {
                             $parents[$row->parent_id][] = $record;
                         }
                         unset($parents[$row->id]);
                     }
                 }
             }
         }
         foreach ($tally as $date => $records) {
             if (!array_key_exists($date, self::$entries[$userid]['dates'])) {
                 self::$entries[$userid]['dates'][$date] = array('forms' => array(), 'person' => array());
             }
             foreach ($records as $record) {
                 if (!array_key_exists($record, $forms)) {
                     I2CE::raiseMessage("{$record} not in forms array.");
                     continue;
                 }
                 if (!array_key_exists($forms[$record], self::$entries[$userid]['dates'][$date]['forms'])) {
                     self::$entries[$userid]['dates'][$date]['forms'][$forms[$record]] = 0;
                 }
                 self::$entries[$userid]['has_forms'] = true;
                 self::$entries[$userid]['dates'][$date]['forms'][$forms[$record]]++;
                 if (array_key_exists($record, $person)) {
                     if (!array_key_exists($person[$record], self::$entries[$userid]['dates'][$date]['person'])) {
                         self::$entries[$userid]['dates'][$date]['person'][$person[$record]] = 0;
                     }
                     self::$entries[$userid]['has_person'] = true;
                     self::$entries[$userid]['dates'][$date]['person'][$person[$record]]++;
                 }
             }
         }
     }
     return true;
 }
 /**
  * Prepare the delete statements for records and entries.
  *
  * @param $delete_type The type of delete statement to prepare.
  * @return boolean
  */
 protected function prepareDeleteStatement($delete_type)
 {
     if (!array_key_exists('delete', self::$prepared) || !is_array(self::$prepared['delete'])) {
         self::$prepared['delete'] = array();
     }
     if (!isset(self::$prepared['delete'][$delete_type])) {
         switch ($delete_type) {
             case "record":
                 self::$prepared['delete'][$delete_type] = $this->db->prepare("DELETE FROM record WHERE id = ?", array('integer'), MDB2_PREPARE_MANIP);
                 break;
             case "entry":
             case "last_entry":
                 self::$prepared['delete'][$delete_type] = $this->db->prepare("DELETE FROM {$delete_type} WHERE record = ?", array('integer'), MDB2_PREPARE_MANIP);
                 break;
             default:
                 I2CE::raiseMessage("Unable to prepare delete statement for {$delete_type}.");
                 return false;
         }
         if (I2CE::pearError(self::$prepared['delete'][$delete_type], "Error preparing delete statement {$delete_type}:")) {
             return false;
         }
     }
     return true;
 }
 public function save($do_check, $user)
 {
     $bin_file = $this->getStorageFile();
     if ($this->temp_file && file_exists($this->temp_file)) {
         //I2CE::raiseMessage("copying from ".$this->temp_file." to $bin_file");
         if (!rename($this->temp_file, $bin_file)) {
             I2CE::raiseError("Failed to open {$bin_file} for binary files!");
             return false;
         }
     } else {
         if (strlen($this->value) > 0 && $this->value != 'from_file') {
             I2CE::raiseMessage("writing from value to {$bin_file}");
             $cH = fopen($bin_file, 'w');
             if (!$cH) {
                 I2CE::raiseError("Failed to open {$bin_file} for binary files!");
                 return false;
             }
             fwrite($cH, $this->value);
             fclose($cH);
         } else {
             I2CE::raiseMessage("No data so not creating: {$bin_file}");
         }
     }
     return parent::save($do_check, $user);
 }
 /**
  * Stores the array of mapped value for a formfield in  {@var $formfield}
  * @parmam boolean $isReportForm Defaults to true.  If true we a sending a report form field
  * If false, we are working with a form field.
  * @param string $reportformfield
  */
 protected function setupMappedValues($reportformfield, $isReportForm = true)
 {
     if ($isReportForm === true) {
         $isReportForm = $this->config->report;
     }
     list($mergekey, $mergereport, $reportformfield) = array_pad(explode(':', $reportformfield, 3), -3, '');
     if ($mergereport) {
         $isReportForm = $mergereport;
     }
     if (is_string($isReportForm)) {
         $this->mapReportFormField($reportformfield, $isReportForm);
         $formfield = $this->fieldMaps[$isReportForm][$reportformfield];
         if (!$this->isMapped($reportformfield, $isReportForm)) {
             return;
         }
     } else {
         $formfield = $reportformfield;
     }
     if ($formfield === false) {
         return;
     }
     if (array_key_exists($formfield, $this->mappedValues)) {
         //we have already gotten the mapped values
         return;
     }
     //we need to get the mapped values
     list($formObj, $fieldObj) = $this->getFormFieldObjects($reportformfield, $isReportForm);
     if (!$formObj instanceof I2CE_Form) {
         //we are dealing with a funcion field which is not mapped so return
         return;
     }
     $mappedValues = array();
     if ($fieldObj instanceof I2CE_FormField) {
         $mappedValues = $fieldObj->getMapOptions();
     }
     if (!is_array($mappedValues)) {
         //just to be sure
         $mappedValues = array();
     }
     //$this->mappedValues[$formfield] = $mappedValues;
     $this->mappedValues[$formfield] = array();
     if (count($mappedValues) > 100) {
         I2CE::raiseMessage("A large amount of values are returned from the setupMappedValues function for CustomReport display for {$reportformfield}.  This should be modified to display a text value instead of the mapped value by joining the appropriate form in the relationship.");
     }
     foreach ($mappedValues as $record) {
         $this->mappedValues[$formfield][$record['value']] = $record['display'];
     }
 }
 /**  
  * @param boolean $check_restart defaults to true in which case if the results are paginated and the offeset is more than the number of results, we restart it setting the page to 1
  * @returns mixed false on failure on succes an array. at index 'results' and  MDB2 buffered result object  at index 'num_results' the
  * number of results that would be found without the limit
  */
 protected function getResults($check_restart = true)
 {
     if (array_key_exists('limit_paginated', $this->defaultOptions) && $this->defaultOptions['limit_paginated']) {
         if (!array_key_exists('limit_page', $this->defaultOptions) || !(is_integer($this->defaultOptions['limit_page']) || ctype_digit($this->defaultOptions['limit_page'])) || (int) $this->defaultOptions['limit_page'] < 1) {
             $this->defaultOptions['limit_page'] = 1;
         }
         if (!array_key_exists('limit_per_page', $this->defaultOptions) || !(is_integer($this->defaultOptions['limit_per_page']) || ctype_digit($this->defaultOptions['limit_per_page'])) || (int) $this->defaultOptions['limit_per_page'] < 1) {
             //we don't have a valid 'limit_per_page'
             $this->defaultOptions['limit_per_page'] = 100;
             //default to 100
         }
         $this->defaultOptions['limit_page'] = (int) $this->defaultOptions['limit_page'];
         $this->defaultOptions['limit_per_page'] = (int) $this->defaultOptions['limit_per_page'];
         $limit_offset = ($this->defaultOptions['limit_page'] - 1) * $this->defaultOptions['limit_per_page'];
         $limit_amount = $this->defaultOptions['limit_per_page'];
     } else {
         $limit_offset = $this->defaultOptions['limit_offset'];
         //$limit_amount = $this->defaultOptions['limit_per_page'];
         $limit_amount = false;
         if ($limit_offset !== false || $limit_offset !== 'false') {
             if (!(is_integer($limit_offset) || ctype_digit($limit_offset)) || $limit_offset < 0) {
                 $limit_offset = 0;
             }
         }
         if ($limit_amount === null || empty($limit_amount) || $limit_amount === 'false') {
             $limit_amount = false;
         }
         if ($limit_amount !== false) {
             if (!(is_integer($limit_amount) || ctype_digit($limit_amount)) || $limit_amount < 1) {
                 $limit_amount = 100;
             }
         }
     }
     if ($this->defaultOptions['sort_order'] == 'none') {
         $sort_order = array();
     } else {
         $sort_order = explode(',', $this->defaultOptions['sort_order'] . '');
         foreach ($sort_order as $i => $field) {
             if ($field == 'none') {
                 unset($sort_order[$i]);
             }
         }
     }
     $sort_order = $this->validateSortFields($sort_order, array_keys($this->fieldData));
     $db = MDB2::singleton();
     if ($limit_offset !== false && $limit_amount !== false) {
         $limit = " LIMIT {$limit_amount} OFFSET {$limit_offset} ";
         $this->row_start = $limit_offset;
         $this->row_amount = $limit_amount;
     } else {
         $limit = '';
         $this->row_start = false;
         $this->row_amount = false;
     }
     $sorts = array();
     foreach ($sort_order as $formfield) {
         if (strlen($formfield) == 0) {
             continue;
         }
         if ($formfield[0] == '-') {
             $sort_field = substr($formfield, 1);
             $sort_postfix = ' DESC';
         } else {
             $sort_field = $formfield;
             $sort_postfix = '';
         }
         $sorts[$sort_field] = '`' . $sort_field . '`' . $sort_postfix;
     }
     $order_by = '';
     if (count($sorts) > 0) {
         $order_by = ' ORDER BY ' . implode(',', $sorts);
     }
     if (array_key_exists('nested_limits', $this->defaultOptions)) {
         $where = $this->processWhere($this->defaultOptions['nested_limits']);
     } else {
         $where = '';
     }
     //I2CE::raiseMessage("where is $where " . print_r( $this->defaultOptions['nested_limits'], true) );
     $fields = array();
     foreach ($this->fieldData as $field => $data) {
         if (array_key_exists('db_field', $data)) {
             if (is_array($data['db_field'])) {
                 foreach ($data['db_field'] as $db_field) {
                     $fields[] = "{$db_field}";
                 }
             } else {
                 $fields[] = $data['db_field'] . ' AS `' . $field . '`';
             }
         } else {
             $fields[] = "entry.{$field} AS `{$field}`";
         }
     }
     if (count($fields) == 0) {
         I2CE::raiseError("No fields to display for UserStatistics report.");
         return false;
     }
     //$qry = "SELECT SQL_CALC_FOUND_ROWS e.*,form.name AS form_name, field.name AS field_name,u.username,IF(e.who = 0, 'I2CE Admin', CONCAT_WS(' ', u.firstname, u.lastname)) AS user FROM entry e LEFT JOIN user u ON u.id = e.who JOIN form_field ff ON e.form_field = ff.id JOIN form ON ff.form = form.id JOIN field ON ff.field = field.id $where $order_by $limit";
     $qry = "SELECT SQL_CALC_FOUND_ROWS " . implode(', ', $fields) . " FROM entry LEFT JOIN user ON user.id = entry.who JOIN form_field ff ON entry.form_field = ff.id JOIN form ON ff.form = form.id JOIN field ON ff.field = field.id JOIN record ON record.id = entry.record {$where} {$order_by} {$limit}";
     I2CE::raiseMessage("query is: {$qry}");
     $res = $db->query($qry);
     if (I2CE::pearError($res, "Could not get results")) {
         return false;
     }
     $num_rows = $db->queryRow("SELECT FOUND_ROWS() AS num_rows");
     if (I2CE::pearError($num_rows, "Could not get total number of results")) {
         $num_rows = false;
     } else {
         $num_rows = (int) $num_rows->num_rows;
     }
     return array('results' => $res, 'num_results' => $num_rows, 'has_total' => false);
 }
Example #17
0
 /**
  * Create a data tree from a report of the selectable forms.  Deisgned to be fed into tree select
  * @param array $fields 
  * @param array $forms An unorderd array of form names whose values we allow to be selected
  * @param array $displayed The displayed forms for the tree
  * @param array $limits An array with keys form names and value limit data
  * @param array $orders An array with keys form names and values array of field orders for that form.  
  *                      If the form name has no orders, we use default ordering for that form based on its displayed firelds
  * @param int $show_hidden 0=non-hidden, 1=All, 2=hidden only.  Defaults to 0
  * @param string $report A report name to use for the query instead of building it from form cache or directly.
  * @return array
  */
 public static function buildReportTree($fields, $forms, $displayed, $limits, $orders = array(), $show_hidden = 0, $report = null)
 {
     if (!is_array($report) || !array_key_exists('report', $report)) {
         return array();
     }
     $report_table = I2CE_CustomReport::getCachedTableName($report['report']);
     if (!$report_table) {
         return array();
     }
     $map = array();
     if (array_key_exists('map', $report)) {
         $map = $report['map'];
     }
     $where = array();
     $displays = array();
     $report_alias = array();
     $formObjs = array();
     $use_link = '';
     foreach ($fields as $formfield) {
         list($form, $link_field) = $formfield;
         $ff = $form . ($link_field ? "+{$link_field}" : "");
         if (array_key_exists($ff, $map)) {
             $report_alias[$ff] = $map[$ff];
         } elseif (array_key_exists($form, $map)) {
             $report_alias[$form] = $map[$form];
             $report_alias[$ff] = $map[$form];
         } else {
             $report_alias[$form] = $form;
             $report_alias[$ff] = $form;
         }
         //if ( array_key_exists( $ff, $limits ) ) {
         //$limit = $limits[$ff];
         //} else
         if (array_key_exists($report_alias[$ff], $limits)) {
             $limit = $limits[$report_alias[$ff]];
         } elseif (array_key_exists($form, $limits)) {
             $limit = $limits[$form];
         } else {
             $limit = array();
         }
         self::addFormIdToLimit($form, $limit);
         $limit = self::showHiddenLimit($limit, $show_hidden);
         /*
         if ( !$show_hidden ) {
             $hidden = $report_alias[$ff] . '+i2ce_hidden';
             $where[] = "( `$hidden` = 0 OR ISNULL( `$hidden` ) )";
         }
         */
         $disp_fields = I2CE_List::getDisplayFields($form);
         if (array_key_exists($form, $orders)) {
             $order = $orders[$form];
         } else {
             $order = I2CE_List::getSortFields($form);
         }
         $sort_list = array();
         //if ( array_key_exists( $form, $displayed ) && $displayed[$form] ) {
         if (array_key_exists($form, $displayed)) {
             $alias_form = $report_alias[$ff];
             if ($displayed[$form]) {
                 $displays[$alias_form]['form'] = $form;
                 if ($use_link == '') {
                     $displays[$alias_form]['link_field'] = $link_field == '' ? $link_field : "{$alias_form}+{$link_field}";
                 } else {
                     $displays[$alias_form]['link_field'] = $use_link;
                     $use_link = '';
                 }
                 foreach ($disp_fields as $disp) {
                     $displays[$alias_form]['fields'][$disp] = $alias_form . "+{$disp}";
                 }
                 foreach ($order as $i => $ord) {
                     if (!is_string($ord)) {
                         unset($order[$i]);
                         continue;
                     }
                     if ($ord[0] == '-') {
                         $field = substr($ord, 1);
                         $all_orders[] = "`{$alias_form}+{$field}` DESC";
                     } else {
                         $field = $ord;
                         $all_orders[] = "`{$alias_form}+{$field}` ASC";
                     }
                 }
             } elseif ($use_link == '') {
                 $use_link = $link_field == '' ? $link_field : "{$alias_form}+{$link_field}";
             }
         }
         if (!array_key_exists($form, $formObjs)) {
             $formObjs[$form] = I2CE_FormFactory::instance()->createContainer($form);
             if (!$formObjs[$form] instanceof I2CE_Form) {
                 I2CE::raiseError("Could not instantiate {$form}");
                 return array();
             }
         }
         self::$curr_alias = $report_alias[$ff];
         $where[] = $formObjs[$form]->generateWhereClause($limit, array("I2CE_DataTree", "getSQLField"));
     }
     $where_clause = "";
     $order_by = "";
     if (count($where) > 0) {
         $where_clause = " WHERE " . implode(' AND ', $where);
     }
     if (count($all_orders) > 0) {
         $order_by = " ORDER BY " . implode(',', $all_orders);
     }
     $qry = "SELECT * FROM {$report_table} {$where_clause} {$order_by}";
     $db = MDB2::singleton();
     I2CE::raiseMessage($qry);
     $res = $db->query($qry);
     if (I2CE::pearError($res, "Invalid report data tree query: ")) {
         return array();
     }
     $phonebook = array();
     $results = array();
     $display_string = array();
     $display_copy = $displays;
     while ($data = $res->fetchRow()) {
         foreach ($displays as $alias => $disp_data) {
             $id_field = strtolower($alias . "+id");
             if ($data->{$id_field} == null || array_key_exists($data->{$id_field}, $phonebook)) {
                 continue;
             }
             $curr = array();
             $add_this = false;
             if (in_array($disp_data['form'], $forms)) {
                 $curr['value'] = $data->{$id_field};
                 $add_this = true;
             }
             if (!$add_this) {
                 $check_ok = false;
                 foreach ($display_copy as $alias_copy => $disp_data_copy) {
                     if ($alias_copy == $alias) {
                         $check_ok = true;
                         continue;
                     }
                     if (!$check_ok) {
                         continue;
                     }
                     if (array_key_exists('link_field', $disp_data_copy) && $disp_data_copy['link_field'] != '') {
                         $link_field_copy = $disp_data_copy['link_field'];
                         if ($data->{$id_field} == $data->{$link_field_copy}) {
                             $add_this = true;
                             break;
                         }
                     }
                 }
             }
             if (!$add_this) {
                 continue;
             }
             if (!array_key_exists($disp_data['form'], $display_string)) {
                 $display_string[$disp_data['form']] = I2CE_List::getDisplayString($disp_data['form']);
             }
             $disp_array = array();
             $disp_str = $display_string[$disp_data['form']];
             $disp_str_arr = explode('%s', $disp_str);
             $fo = $formObjs[$disp_data['form']];
             $disp_count = 0;
             foreach ($disp_data['fields'] as $field => $dbfield) {
                 $disp_count++;
                 if ($dbfield == $disp_data['link_field']) {
                     // Don't include the data from the link field since it will already be there.
                     if ($disp_count == 1) {
                         unset($disp_str_arr[$disp_count]);
                     } else {
                         unset($disp_str_arr[$disp_count - 1]);
                     }
                     continue;
                 }
                 $dbfield = strtolower($dbfield);
                 $fieldObj = $fo->getField($field);
                 if (!$fieldObj instanceof I2CE_FormField) {
                     I2CE::raiseError("Could not get field {$field}");
                     continue;
                 }
                 if (isset($data->{$dbfield})) {
                     $fieldObj->setFromDB($data->{$dbfield});
                     $disp_array[$field] = $fieldObj->getDisplayValue();
                 } else {
                     $disp_array[$field] = null;
                 }
             }
             $disp_str = implode('%s', $disp_str_arr);
             $display = vsprintf($disp_str, $disp_array);
             $curr['display'] = $display;
             $phonebook[$data->{$id_field}] =& $curr;
             if ($disp_data['link_field'] != '') {
                 $link_field = $disp_data['link_field'];
                 if (array_key_exists($data->{$link_field}, $phonebook)) {
                     $add_to =& $phonebook[$data->{$link_field}];
                     if (!array_key_exists('children', $phonebook[$data->{$link_field}])) {
                         $phonebook[$data->{$link_field}]['children'] = array();
                     }
                     $phonebook[$data->{$link_field}]['children'][] =& $curr;
                 } else {
                     //I2CE::raiseMessage( "Couldn't find $link_field " . $data->$link_field . " in phonebook " );
                 }
             } else {
                 $results[] =& $curr;
             }
             unset($curr);
         }
     }
     return $results;
 }
 /**
  * Build the data tree for the given list of fields 
  * and limits.  This is called by I2CE_List::buildDataTree.
  * See that for more details
  * @see I2CE_List::buildDataTree
  * @param array $fields The fields to build the tree
  * @param array $forms The selectable forms
  * @param array $displayed The displayed forms for the tree
  * @param array $limits The list of limits for each form.
  * @param array $orders The order fields for each given form
  * @param int $show_hidden 0=non-hidden, 1=All, 2=hidden only.  Defaults to 0
  * @return array The ordered list of all entries in the tree.
  */
 public function buildDataTree($fields, $forms, $displayed, $limits, $orders, $show_hidden = 0)
 {
     $prev_form = false;
     $form_aliases = array();
     $selects = array();
     $displays = array();
     $all_orders = array();
     $formObjs = array();
     $skip_links = array();
     $skip_link_fields = array();
     $this->preserve_ids = true;
     foreach ($fields as $formfield) {
         list($form, $link_field) = $formfield;
         $cachedForm = new I2CE_CachedForm($form);
         $cachedForm->generateCachedTable(false);
         unset($cachedForm);
         $alias_form = $form . ($link_field ? "+{$link_field}" : "");
         if (array_key_exists($alias_form, $limits)) {
             $limit = $limits[$alias_form];
         } elseif (array_key_exists($form, $limits)) {
             $limit = $limits[$form];
         } else {
             $limit = array();
         }
         self::addFormIdToLimit($form, $limit);
         $limit = I2CE_List::showHiddenLimit($limit, $show_hidden);
         $disp_fields = I2CE_List::getDisplayFields($form);
         $field_list = $disp_fields;
         $field_list[] = 'id';
         if ($link_field && !in_array($link_field, $field_list)) {
             $field_list[] = $link_field;
         }
         if (array_key_exists($form, $orders)) {
             $order = $orders[$form];
         } else {
             $order = I2CE_List::getSortFields($form);
         }
         $sort_list = array();
         if (array_key_exists($form, $displayed) && $displayed[$form]) {
             $displays[$alias_form]['form'] = $form;
             $displays[$alias_form]['link_field'] = $link_field;
             foreach ($disp_fields as $disp) {
                 $displays[$alias_form]['fields'][$disp] = "{$alias_form}+{$disp}";
             }
             foreach ($order as $i => $ord) {
                 if (!is_string($ord)) {
                     unset($order[$i]);
                     continue;
                 }
                 if ($ord[0] == '-') {
                     $field = substr($ord, 1);
                     $all_orders[] = "`{$alias_form}`.`{$field}` DESC";
                 } else {
                     $field = $ord;
                     $all_orders[] = "`{$alias_form}`.`{$field}` ASC";
                 }
                 if (!in_array($field, $field_list)) {
                     $sort_list[] = $field;
                 }
             }
         } else {
             $skip_link_fields[$alias_form] = $link_field;
         }
         if (!array_key_exists($form, $formObjs)) {
             $formObjs[$form] = I2CE_FormFactory::instance()->createContainer($form);
             if (!$formObjs[$form] instanceof I2CE_Form) {
                 I2CE::raiseError("Could not instantiate {$form}");
                 return array();
             }
         }
         $where = false;
         if (is_array($limit) && count($limit) > 0) {
             $where = $formObjs[$form]->generateWhereClause($limit, array("I2CE_FormStorage_cached", "getSQLField"));
         }
         $query = $this->getRequiredFieldsQuery($form, array_merge($field_list, $sort_list), null, false, array("I2CE_FormStorage_cached", "getSQLField"));
         if (is_array($prev_form) && array_key_exists('form', $prev_form)) {
             if ($prev_form['form'] == $form) {
                 $froms[$alias_form] = " LEFT JOIN ";
             } else {
                 $froms[$alias_form] = " LEFT JOIN ";
             }
         } else {
             $froms[$alias_form] = "";
         }
         $froms[$alias_form] .= "({$query}" . ($where ? " WHERE " . $where : "") . ") AS `{$alias_form}`";
         if ($link_field) {
             $join_ons = array();
             $ff = $formObjs[$form]->getField($link_field);
             if ($ff instanceof I2CE_FormField_MAPPED) {
                 foreach ($ff->getSelectableForms() as $link_form) {
                     if (array_key_exists($link_form, $form_aliases)) {
                         foreach ($form_aliases[$link_form] as $link_alias) {
                             $join_ons[] = "`{$alias_form}`.`{$link_field}` = `{$link_alias}`.`id`";
                             if (!array_key_exists($link_alias, $displays) && array_key_exists($link_alias, $skip_link_fields)) {
                                 $skip_links[$alias_form . '+' . $link_field] = $link_alias . '+' . $skip_link_fields[$link_alias];
                             }
                         }
                     }
                 }
             } else {
                 I2CE::raiseMessage("Not sure what to link for {$form} {$link_field} so guessing.");
                 $join_ons[] = "`{$alias_form}`.`{$link_field}` = `" . $prev_form['alias'] . "`.`id`";
             }
             if (count($join_ons) > 0) {
                 $froms[$alias_form] .= " ON (" . implode(' OR ', $join_ons) . ") ";
             } else {
                 I2CE::raiseError("Don't know how to join on {$form} {$link_field}");
                 return array();
             }
         }
         foreach ($field_list as $field) {
             $selects[] = "`{$alias_form}`.`{$field}` AS `{$alias_form}+{$field}`";
         }
         $prev_form = array('form' => $form, 'alias' => $alias_form);
         $form_aliases[$form][] = $alias_form;
     }
     $or_wheres = array();
     foreach ($forms as $selectable) {
         if (array_key_exists($selectable, $form_aliases)) {
             foreach ($form_aliases[$selectable] as $required_form) {
                 $or_wheres[] = "`{$required_form}`.`id` IS NOT NULL";
             }
         }
     }
     $join_query = "SELECT " . implode(',', $selects) . " FROM " . implode('', $froms) . (count($or_wheres) > 0 ? " WHERE " . implode(' OR ', $or_wheres) : "") . (count($all_orders) > 0 ? " ORDER BY " . implode(',', $all_orders) : "");
     //I2CE::raiseMessage( $join_query );
     $res = $this->db->query($join_query);
     if (I2CE::pearError($res, "Bad query -- {$join_query}")) {
         return array();
     }
     $prev_ids = array();
     $results = array();
     $phonebook = array();
     $display_string = array();
     foreach ($displays as $fix_link_alias => &$fix_link_disp_data) {
         if (array_key_exists('link_field', $fix_link_disp_data) && $fix_link_disp_data['link_field'] != '') {
             $full_link_field = strtolower($fix_link_alias . "+" . $fix_link_disp_data['link_field']);
             while (array_key_exists($full_link_field, $skip_links)) {
                 $full_link_field = $skip_links[$full_link_field];
             }
             $fix_link_disp_data['link_field'] = $full_link_field;
         }
     }
     $display_copy = $displays;
     while ($data = $res->fetchRow()) {
         unset($prev_disp);
         foreach ($displays as $alias => $disp_data) {
             $id_field = strtolower($alias . "+id");
             if ($data->{$id_field} == null || array_key_exists($data->{$id_field}, $phonebook)) {
                 continue;
             }
             $curr = array();
             $add_this = false;
             if (in_array($disp_data['form'], $forms)) {
                 $curr['value'] = $data->{$id_field};
                 $add_this = true;
             }
             if (!$add_this) {
                 $check_ok = false;
                 foreach ($display_copy as $alias_copy => $disp_data_copy) {
                     if ($alias_copy == $alias) {
                         $check_ok = true;
                         continue;
                     }
                     if (!$check_ok) {
                         continue;
                     }
                     if (array_key_exists('link_field', $disp_data_copy) && $disp_data_copy['link_field'] != '') {
                         $link_field_copy = $disp_data_copy['link_field'];
                         if ($data->{$id_field} == $data->{$link_field_copy}) {
                             $add_this = true;
                             break;
                         }
                     }
                 }
             }
             if (!$add_this) {
                 continue;
             }
             if (!array_key_exists($disp_data['form'], $display_string)) {
                 $display_string[$disp_data['form']] = I2CE_List::getDisplayString($disp_data['form']);
             }
             $disp_array = array();
             $disp_str = $display_string[$disp_data['form']];
             $disp_str_arr = explode("%s", $disp_str);
             $fo = $formObjs[$disp_data['form']];
             $disp_count = 0;
             foreach ($disp_data['fields'] as $field => $dbfield) {
                 $disp_count++;
                 if ($field == $disp_data['link_field']) {
                     // Don't include the data from the link field since it will already
                     // be in the tree above it.
                     if ($disp_count == 1) {
                         unset($disp_str_arr[$disp_count]);
                     } else {
                         unset($disp_str_arr[$disp_count - 1]);
                     }
                     continue;
                 }
                 $dbfield = strtolower($dbfield);
                 $fieldObj = $fo->getField($field);
                 if (!$fieldObj instanceof I2CE_FormField) {
                     I2CE::raiseError("Could not get field {$field}");
                     continue;
                 }
                 if (isset($data->{$dbfield})) {
                     $fieldObj->setFromDB($data->{$dbfield});
                     $disp_array[$field] = $fieldObj->getDisplayValue();
                 } else {
                     $disp_array[$field] = null;
                 }
             }
             $disp_str = implode('%s', $disp_str_arr);
             $display = vsprintf($disp_str, $disp_array);
             //$display = $data->$disp_data['fields']['name'];
             $curr['display'] = $display;
             $phonebook[$data->{$id_field}] =& $curr;
             if ($disp_data['link_field'] != '') {
                 $link_field = $disp_data['link_field'];
                 if (array_key_exists($data->{$link_field}, $phonebook)) {
                     $add_to =& $phonebook[$data->{$link_field}];
                     if (!array_key_exists('children', $phonebook[$data->{$link_field}])) {
                         $phonebook[$data->{$link_field}]['children'] = array();
                     }
                     $phonebook[$data->{$link_field}]['children'][] =& $curr;
                 } else {
                     I2CE::raiseMessage("Couldn't find {$link_field} " . $data->{$link_field} . " in phonebook");
                 }
             } else {
                 $results[] =& $curr;
             }
             unset($curr);
         }
     }
     $this->preserve_ids = false;
     return $results;
 }
 }
 $qry = array();
 parse_str($comp['query'], $qry);
 if (!is_array($qry) || !array_key_exists('type', $qry)) {
     echo "Skipping(1): " . $a->textContent . " : href=" . $href . "\n";
     continue;
 }
 $type = $qry['type'];
 unset($qry['type']);
 $qry['form'] = $type;
 if ($li->hasAttribute('task')) {
     $qry['task'] = $li->getAttribute('task');
 }
 $h2_list = $template->query('preceding::h2[1]', $li);
 if ($h2_list->length != 1) {
     I2CE::raiseMessage("No h2 before this node");
 } else {
     $qry['category'] = $h2_list->item(0)->textContent;
 }
 $h3_list = $template->query('preceding::h3[1]', $li);
 if ($h3_list->length == 1) {
     //check to see if preceeding h2 is same as current category
     $h2_list = $template->query('preceding::h2[1]', $h3_list->item(0));
     if ($h2_list->length == 1 && $h2_list->item(0)->textContent == $qry['category']) {
         $qry['subcategory'] = $h3_list->item(0)->textContent;
     }
 }
 $mods = $template->query("ancestor-or-self::*[@type='module'][1]", $li);
 if ($mods->length == 1 && ($mod = $mods->item(0)->getAttribute('name'))) {
     $qry['mods'] = $mod;
 }
 protected function clear_service_cache($form)
 {
     if (function_exists('apc_fetch')) {
         $apc_root = 'FS_Service_(' . $form . ')_' . get_class($this) . '_';
         $iter = new APCIterator('user', '/^' . preg_quote($apc_root) . '/');
         foreach ($iter as $item) {
             I2CE::raiseMessage("Deleting {$apc_root}:  " . $item['key']);
             apc_delete($item['key']);
         }
     }
 }
 protected function setSegmentValue($segment, $fieldObj, $key, $value, $options = array())
 {
     if (array_key_exists('eval', $options) && is_callable($options['eval'])) {
         $value = call_user_func($options['eval'], $value);
     }
     if ($fieldObj instanceof I2CE_FormField_IMAGE) {
         $fieldObj->setFromDB($value);
         try {
             $segment->setImageFromField($key, $fieldObj, $options);
         } catch (Exception $e) {
             I2CE::raiseMessage("Cant set image {$key}");
             //It's ok if it's not there so don't do anything.
         }
     } else {
         if ($fieldObj instanceof I2CE_FormField_MAP_MULT && array_key_exists('separator', $options)) {
             $value = explode(",", $value);
             foreach ($value as &$v) {
                 $v = trim($v);
             }
             unset($v);
             $value = implode(str_replace('\\n', "\n", $options['separator']), $value);
         }
         try {
             $segment->setVars($key, $value, $this->encoding, $this->charset);
         } catch (Exception $e) {
             //It's ok if it's not there so don't do anything.
         }
     }
 }
 /**
  * Do the pre action for exam results
  */
 protected function action_pre_exam_results()
 {
     if ($this->request_exists('paper')) {
         $this->data['paper'] = $this->factory->createContainer($this->request('paper'));
         if (!$this->data['paper'] instanceof I2CE_SimpleList || $this->data['paper']->getName() != 'paper') {
             I2CE::raiseMessage("not a paper form " . get_class($this->data['paper']));
             $this->template->addFile('edit_exam_exam_results_invalid_paper.html');
             $this->data['invalid'] = true;
         } else {
             $this->data['paper']->populate();
             if ($this->data['paper']->name == '') {
                 I2CE::raiseMessage("name field is blank");
                 $this->template->addFile('edit_exam_exam_results_invalid_paper.html');
                 $this->data['invalid'] = true;
             } else {
                 $this->template->addHeaderLink('mootools-more.js');
                 $this->template->addHeaderLink('I2CE_InputFormatter.js');
                 $personExam = $this->factory->createContainer('person_exam|0');
                 $this->template->setForm($personExam, $this->data['detailsNode']);
                 $this->template->setDisplayData("exam_paper_name", $this->data['paper']->name, $this->data['titleNode']);
             }
         }
     } else {
         I2CE::raiseMessage("no paper field request");
         $this->template->addFile('edit_exam_exam_results_invalid_paper.html');
         $this->data['invalid'] = true;
     }
 }
 /**
  * Generates the cahced table for the form
  * @param boolean $check_stale.  Defaults to true.  If false, it skips the staleness check
  * @param boolean $check_dirty.  Defaults to true.  If false, it skips the dirtiness check
  */
 public function generateCachedTable($check_stale = true, $check_dirty = true)
 {
     $time = time();
     if ($check_stale && !$this->isStale()) {
         //I2CE::raiseMessage("Skipping cached table for {$this->form} as it is not stale" );
         return true;
     }
     if ($this->tableExists()) {
         if ($check_dirty && !I2CE_Module_CachedForms::formIsDirty($this->form)) {
             //I2CE::raiseMessage("Skipping cached table for {$this->form} as it is not dirty" );
             return true;
         }
         I2CE::raiseMessage("The form {$this->form} is dirty");
     }
     I2CE::getConfig()->modules->CachedForms->status->{$this->form} = 'in_progress';
     if (!$this->tableExists() && !$this->createCacheTable()) {
         return false;
     }
     I2CE::raiseError("Populating fields for {$this->form}");
     if ($this->formMech instanceof I2CE_FormStorage_DB) {
         if (!$this->fastPopulate($check_dirty)) {
             return false;
         }
     } else {
         if (!$this->slowPopulate($check_dirty)) {
             return false;
         }
     }
     I2CE::raiseMessage("Populated {$this->form} at {$time}:" . date('r', $time) . "\n");
     I2CE::getConfig()->modules->CachedForms->times->generation->{$this->form} = $time;
     I2CE::getConfig()->modules->CachedForms->status->{$this->form} = 'done';
     I2CE_Module_CachedForms::markFormClean($this->form, $time);
     //will mark the form as clean if the dirty timestamp  does not exceed time
     return true;
 }
Example #24
0
 protected function pushMessage($message, $i = 0)
 {
     I2CE::raiseMessage($message);
     $js_message = '<script type="text/javascript">addMessage("' . str_replace("\n", '<br/>', addcslashes($message, '"\\')) . '",' . $i . ");</script>\n";
     echo $js_message;
     flush();
 }
 protected function raiseError($msg)
 {
     I2CE::raiseMessage($msg);
     if (is_callable($this->callback)) {
         call_user_func_array($this->callback, array($msg));
     }
 }
 /**
  * Perform the command line action for this page.
  * @param array $args
  * @param array $request_remainder
  * @return boolean
  */
 public function actionCommandLine($args, $request_remainder)
 {
     $usModule = I2CE_ModuleFactory::instance()->getClass("UserStatistics");
     $action = "update";
     if (count($request_remainder) > 0) {
         $action = array_shift($request_remainder);
     }
     switch ($action) {
         case "recreate":
             if ($usModule->cacheUserStatistics(true)) {
                 I2CE::raiseMessage("Re-Cached user statistics.");
             } else {
                 I2CE::raiseError("Failed to re-cache user statistics.");
             }
             break;
         case "recreateForce":
             if ($usModule->cacheUserStatistics(true, true)) {
                 I2CE::raiseMessage("Re-Cached user statistics.");
             } else {
                 I2CE::raiseError("Failed to re-cache user statistics.");
             }
             break;
         case "force":
             if ($usModule->cacheUserStatistics(false, true)) {
                 I2CE::raiseMessage("Updated user statistics.");
             } else {
                 I2CE::raiseError("Failed to force cache user statistics.");
             }
             break;
         default:
             if ($usModule->cacheUserStatistics()) {
                 I2CE::raiseMessage("Updated user statistics.");
             } else {
                 I2CE::raiseError("Failed to cache user statistics.");
             }
             break;
     }
 }