public function handleMessages($page)
 {
     $template = $page->getTemplate();
     if (!is_array($this->immediate_messages)) {
         $this->immediate_messages = array();
     }
     if (!array_key_exists('user_messages', $_SESSION) || !is_array($_SESSION['user_messages'])) {
         $_SESSION['user_messages'] = array();
     }
     if (!array_key_exists('current', $_SESSION['user_messages']) || !is_array($_SESSION['user_messages']['current'])) {
         $_SESSION['user_messages']['current'] = array();
     }
     foreach ($_SESSION['user_messages']['current'] as $class => $msgs) {
         if (!array_key_exists($class, $this->immediate_messages)) {
             $this->immediate_messages[$class] = array();
         }
         $this->immediate_messages[$class] = array_merge($this->immediate_messages[$class], $msgs);
     }
     foreach ($this->immediate_messages as $class => $msgs) {
         $msgs = array_unique($msgs);
         I2CE_ModuleFactory::callHooks("display_messages_{$class}", array('template' => $template, 'messages' => $msgs));
     }
     $this->immediate_messages = array();
     $_SESSION['user_messages']['current'] = array();
 }
 /**
  * Setup list of enumerated values for this field.
  */
 public function setupEnum($display = 'default')
 {
     if (count($this->enum_values) > 0) {
         return;
     }
     $values = array();
     if (($enum = $this->getOptionsByPath("meta/enum")) !== null) {
         if (array_key_exists('data', $enum)) {
             //$values = array_merge( $values, $enum['data'] );
             $values += $enum['data'];
         }
         if (array_key_exists('hook', $enum)) {
             $hooks = I2CE_ModuleFactory::callHooks($enum['hook']);
             foreach ($hooks as $hook_data) {
                 //$values = array_merge( $values, $hook_data );
                 $values += $hook_data;
             }
         }
         if (array_key_exists('method', $enum)) {
             if (array_key_exists('static', $enum['method']) || array_key_exists('module', $enum['method'])) {
                 if (array_key_exists('module', $enum['method'])) {
                     foreach ($enum['method']['module'] as $module => $method) {
                         $modObj = I2CE_ModuleFactory::instance()->getClass($module);
                         if (!$modObj || !method_exists($modObj, $method)) {
                             I2CE::raiseError("No module found for {$module} when getting enum values or {$method} doesn't exist for " . $this->name);
                             continue;
                         }
                         //$values = array_merge( $values, $modObj->{$method}() );
                         $values += $modObj->{$method}();
                     }
                 }
                 if (array_key_exists('static', $enum['method'])) {
                     foreach ($enum['method']['static'] as $class => $method) {
                         if (!class_exists($class) || !method_exists($class, $method)) {
                             I2CE::raiseError("Couldn't find class {$class} or method {$method} in class for enum values.");
                             continue;
                         }
                         //$values = array_merge( $values, call_user_func( array( $class, $method ) ) );
                         $values += call_user_func(array($class, $method));
                     }
                 }
             } else {
                 I2CE::raiseError("No valid arguments for call in ENUM for " . $this->name);
             }
         }
         if (array_key_exists('sort', $enum)) {
             if ($enum['sort'] == "key") {
                 ksort($values);
             } elseif ($enum['sort'] == "value") {
                 asort($values);
             }
         } else {
             // Default sort by values
             asort($values);
         }
     } else {
         I2CE::raiseError("No enum setting for " . $this->name);
     }
     $this->enum_values = $values;
 }
 public function __construct()
 {
     I2CE_ModuleFactory::callHooks('formfactory_pre_construct');
     $this->classes = I2CE::getConfig()->modules->forms->forms;
     $this->classHierarchy = array();
     parent::__construct();
     I2CE_ModuleFactory::callHooks('formfactory_post_construct');
 }
Esempio n. 4
0
/**
 * The autoload function is used to load class files when needed
 * 
 * This function will be used to load any class files when they
 * are required instead of in every file.
 * 
 * It searchs the configuration array for the common class directory
 * as well as the class directory specifically for this project.
 * @global array
 * @param string $class_name The name of the class being loaded
 */
function i2ce_class_autoload($class_name)
{
    $class_file = I2CE::getfileSearch()->search('CLASSES', $class_name . '.php');
    $class_found = false;
    if ($class_file) {
        require_once $class_file;
        if (class_exists($class_name, false) || interface_exists($class_name, false)) {
            $class_found = true;
        } else {
            I2CE::raiseError("Defintion for class {$class_name} is not contained in {$class_file}", E_USER_WARNING);
        }
    }
    if (!$class_found) {
        $classes = I2CE_ModuleFactory::callHooks('autoload_search_for_class', $class_name);
        $count = count($classes);
        foreach ($classes as $class) {
            if (!is_string($class) || strlen($class) == 0) {
                continue;
            }
            if (false === eval($class)) {
                I2CE::raiseError("While looking for {$class_name}, could not parse: {$class}");
            }
            if (class_exists($class_name, false)) {
                $class_found = true;
                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);
    }
}
 public function appendChildTemplate($form, $set_on_node = null, $template = false, $tag = 'div', $appendNode = null)
 {
     end($this->parentObjs);
     if (!($parentObject = current($this->parentObjs)) instanceof I2CE_Form) {
         I2CE::raiseError("Unexpected object");
         return false;
     }
     $auto_template = array_key_exists('children', $this->args) && is_array($this->args['children']) && array_key_exists($form, $this->args['children']) && is_array($this->args['children'][$form]) && array_key_exists('auto_template', $this->args['children'][$form]) && is_array($this->args['children'][$form]['auto_template']) && !(array_key_exists('disabled', $this->args['children'][$form]['auto_template']) && $this->args['children'][$form]['auto_template']['disabled']);
     if (!$auto_template) {
         if (!array_key_exists($form, $parentObject->children) || !is_array($parentObject->children[$form])) {
             return true;
         }
         $child_forms = $parentObject->children[$form];
     } else {
         if (!array_key_exists($form, $parentObject->children) || !is_array($parentObject->children[$form])) {
             $child_forms = array(I2CE_FormFactory::instance()->createContainer($form));
         } else {
             $child_forms = $parentObject->children[$form];
         }
     }
     if ($appendNode === null) {
         $appendNode = $form;
     }
     if (is_string($appendNode)) {
         $appendNode = $this->template->getElementById($appendNode);
     }
     if (!$appendNode instanceof DOMNode) {
         I2CE::raiseError("Do not know where to add child form {$form} ");
         return false;
     }
     foreach ($child_forms as $formObj) {
         if ($formObj instanceof I2CE_Form) {
             I2CE_ModuleFactory::callHooks('pre_add_child_form_' . $form, array('form' => $formObj, 'page' => $this, 'set_on_node' => $set_on_node, 'append_node' => $appendNode));
         }
         if (!$auto_template) {
             if (!$formObj instanceof I2CE_Form) {
                 continue;
             }
             if (!is_string($template) || !$template) {
                 $template = $this->getChildTemplate($form);
             }
             $node = $this->template->appendFileByNode($template, $tag, $appendNode);
         } else {
             $node = $this->generateAutoChildTemplate($formObj, $this->args['children'][$form]['auto_template'], $appendNode);
         }
         if (!$node instanceof DOMNode) {
             I2CE::raiseError("Could not find template {$template} for child form {$form} of " . $parentObject->getName());
             return false;
         }
         if ($formObj instanceof I2CE_Form) {
             $this->template->setForm($formObj, $node);
             if ($set_on_node !== null) {
                 $this->template->setForm($formObj, $set_on_node);
             }
             I2CE_ModuleFactory::callHooks('post_add_child_form_' . $form, array('form' => $formObj, 'node' => $node, 'page' => $this, 'set_on_node' => $set_on_node, 'append_node' => $appendNode));
             if (!$this->action_children($formObj, $node)) {
                 I2CE::raiseError("Couldn't display child " . $form);
             }
         }
     }
     return $appendNode;
 }
 /**
  * Save the objects to the database.
  * 
  * Save the default object being edited
  * Most saving will be handled by the processRow functions.
  * @global array
  */
 protected function save()
 {
     foreach (array_keys($this->files) as $key) {
         if (!$this->processHeaderRow($key)) {
             return false;
         }
         while ($this->processRow($key)) {
             if (!$this->saveRow($key)) {
                 return false;
             }
         }
     }
     I2CE_ModuleFactory::callHooks('post_save_csv_upload_' . $this->module . '_page_' . $this->page, $this);
     return true;
 }
 /**
  * Validate all fields that are marked as required or unique.
  *
  * This will check all the fields in this form and if they're required or unique it
  * will perform the required checks 
  */
 public function validate()
 {
     I2CE_ModuleFactory::callHooks("validate_form", $this);
     I2CE_ModuleFactory::callHooks("validate_form_" . $this->getName(), $this);
     foreach ($this->fields as $field_name => $field_obj) {
         I2CE_ModuleFactory::callHooks("validate_formfield", $field_obj);
         I2CE_ModuleFactory::callHooks("validate_form_" . $this->getName() . "_field_" . $field_name, $field_obj);
     }
 }
Esempio n. 8
0
 public static function listOptions($form_name, $show_hidden = 0, $select_fields = array())
 {
     $where = array();
     if (!is_array($select_fields)) {
         $select_fields = array($select_fields);
     }
     foreach ($select_fields as $select_field) {
         if (!$select_field instanceof I2CE_FormField_MAPPED || !$select_field->isSetValue() || !$select_field->isValid() || !($select_form = $select_field->getContainer()) instanceof I2CE_Form || $select_form->getName() != $form_name) {
             continue;
         }
         $where[] = array('operator' => 'FIELD_LIMIT', 'field' => $select_field->getName(), 'style' => 'equals', 'data' => array('value' => $select_field->getDBValue()));
     }
     $add_limits = array();
     foreach (I2CE_ModuleFactory::callHooks("get_limit_add_form_{$form_name}_id") as $add_limit) {
         if (!is_array($add_limit) || !array_key_exists($form_name, $add_limit) || !is_array($add_limit[$form_name])) {
             continue;
         }
         $add_limits[] = $add_limit;
     }
     $where = array_merge($where, $add_limits);
     if (count($where) > 0) {
         $where = array('operator' => 'AND', 'operand' => $where);
     }
     $forms = array($form_name);
     $limits = array($form_name => $where);
     $limits = array($form_name => $where);
     $orders = array($form_name => self::getSortFields($form_name));
     $fields = array($form_name);
     $data = I2CE_DataTree::buildDataTree($fields, $forms, $limits, $orders, $show_hidden);
     $data = I2CE_DataTree::flattenDataTree($data);
     return $data;
 }
Esempio n. 9
0
 protected function actionMenu()
 {
     I2CE_ModuleFactory::callHooks('pre_admin_menu_modules', array('page' => $this));
     $this->template->setBodyId("adminPage");
     $config = I2CE::getConfig()->config;
     $this->template->setAttribute("class", "active", "menuConfigure", "a[@href='configure']");
     $this->template->appendFileById("menu_configure.html", "ul", "menuConfigure");
     $this->template->setAttribute("class", "active", "menuConfigureModules", "a[@href='admin/modules']");
     if ($this->isGet() && $this->get_exists('redirect') && $this->get('redirect')) {
         $this->template->setDisplayData("redirect", $this->get('redirect'));
     }
     $siteModule = '';
     $this->mod_factory->checkForNewModules();
     //re-read all the module information available to the system
     $config->setIfIsSet($siteModule, 'site/module');
     //now we get the sub-modules of the current module
     if ($this->isGet() && $this->get_exists('possibles')) {
         $modules = explode(':', $this->get('possibles'));
     } else {
         if ($this->shortname == 'I2CE') {
             $modules = array();
             if ($siteModule) {
                 $modules = $this->mod_factory->checkForNewModules($siteModule);
             }
             $t_modules = $this->mod_factory->checkForNewModules('I2CE');
             foreach ($t_modules as $module) {
                 if (!in_array($module, $modules)) {
                     $modules[] = $module;
                 }
             }
         } else {
             $modules = $this->mod_factory->checkForNewModules($this->shortname);
         }
     }
     $this->template->addHeaderLink("admin.css");
     $this->template->addHeaderLink("mootools-core.js");
     $this->template->addHeaderLink("admin.js");
     $cats = array();
     foreach ($modules as $module) {
         $dispName = $config->data->{$module}->displayName;
         if ($dispName != 'I2CE') {
             $dispName = preg_replace('/^I2CE\\s+/', '', $dispName);
         }
         if (isset($config->data->{$module}->category)) {
             $cats[$config->data->{$module}->category][$module] = $dispName;
         } else {
             $cats['UNCATEGORIZED'][$module] = $dispName;
         }
     }
     ksort($cats);
     $compare = create_function('$m,$n', 'return strcasecmp($m,$n);');
     foreach ($cats as $cat => $modules) {
         uasort($modules, $compare);
         $cats[$cat] = $modules;
     }
     $menuNode = $this->template->addFile("module_menu.html", "div");
     $displayData = array('module_link' => 'link', 'module_description' => 'description', 'module_email' => 'email', 'module_email_2' => 'email', 'module_version' => 'version', 'module_creator' => 'creator', 'module_name' => 'displayName');
     $possibles = array();
     $configurator = new I2CE_Configurator(I2CE::getConfig());
     foreach ($cats as $cat => $modList) {
         $catNode = $this->template->appendFileById("module_category.html", "div", "modules");
         if (!$catNode instanceof DOMNode) {
             continue;
         }
         if ($cat != 'UNCATEGORIZED') {
             $this->template->setDisplayData("module_category", $cat, $catNode);
         } else {
             $this->template->setDisplayData("module_category", 'Uncategorized', $catNode);
         }
         foreach ($modList as $module => $displayName) {
             $conflicting = false;
             $modNode = $this->template->appendFileByName("module_module.html", "li", "module_list", 0, $catNode);
             if (!$modNode instanceof DOMNode) {
                 continue;
             }
             $modNode->setAttribute('id', 'tr_' . $module);
             $modNode->setAttribute('name', $module);
             $data = $config->data->{$module};
             $origEnableNode = $this->template->getElementByName('module_enable', 0);
             if ($module == 'I2CE') {
                 $origEnableNode->parentNode->removeChild($origEnableNode);
             } else {
                 if ($module == $config->site->module) {
                     $origEnableNode->parentNode->removeChild($origEnableNode);
                 } else {
                     $reqs = $configurator->getDependencyList($module);
                     $badness = '';
                     $origEnableNode->setAttribute('id', $module);
                     if (array_key_exists('badness', $reqs) && !empty($reqs['badness'])) {
                         $badness = $reqs['badness'];
                         if ($this->mod_factory->isEnabled($module)) {
                             $checked = "checked='checked' disabled='disabled'";
                             //shouldn't be
                         } else {
                             $checked = ' disabled="disabled"';
                         }
                         $conflicting = true;
                         $modNode->setAttribute('class', 'conflict');
                         $deps = implode(',', $reqs['requirements']);
                         $optional = implode(',', $reqs['enable']);
                         $conflicts = implode(',', $reqs['conflicts']);
                         $html = " <div class='check'  deps='{$deps}' cons='{$conflicts}' opt='{$optional}'>\n    <input type='checkbox' name='modules[]' value='{$module}' {$checked} id='input_enable_{$module}' />\n  </div>\n";
                         $origEnableNode->parentNode->replaceChild($this->template->importText($html), $origEnableNode);
                     } else {
                         if ($configurator->moduleRequires($module, $data->version, $config->site->module)) {
                             if ($this->mod_factory->isEnabled($module)) {
                                 $checked = "checked='checked'";
                             } else {
                                 $checked = '';
                             }
                             $deps = implode(',', $reqs['requirements']);
                             $optional = implode(',', $reqs['enable']);
                             $conflicts = implode(',', $reqs['conflicts']);
                             $html = "<div class='check'  deps='{$deps}' cons='{$conflicts}' opt='{$optional}'>\n    <input type='hidden' name='modules[]' value='{$module}' id='input_enable_{$module}' />\n    <input type='checkbox' {$checked} disabled='disabled' value='{$module}' {$checked} ' />\n  </div>\n";
                             $origEnableNode->parentNode->replaceChild($this->template->importText($html), $origEnableNode);
                         } else {
                             if ($configurator->moduleConflicts($module, $data->version, $config->site->module)) {
                                 if ($this->mod_factory->isEnabled($module)) {
                                     $checked = "checked='checked' disabled='disabled'";
                                 } else {
                                     $checked = ' disabled="disabled"';
                                 }
                                 $conflicting = true;
                                 $modNode->setAttribute('class', 'conflict');
                                 $deps = implode(',', $reqs['requirements']);
                                 $optional = implode(',', $reqs['enable']);
                                 $conflicts = implode(',', $reqs['conflicts']);
                                 $html = " <div class='check' id='{$module}' deps='{$deps}' cons='{$conflicts}' opt='{$optional}'>\n    <input type='checkbox' name='modules[]' value='{$module}' {$checked} id='input_enable_{$module}' />\n  </div>\n";
                                 $origEnableNode->parentNode->replaceChild($this->template->importText($html), $origEnableNode);
                             } else {
                                 if ($this->mod_factory->isEnabled($module)) {
                                     $checked = "checked='checked'";
                                 } else {
                                     $checked = '';
                                 }
                                 $deps = implode(',', $reqs['requirements']);
                                 $optional = implode(',', $reqs['enable']);
                                 $conflicts = implode(',', $reqs['conflicts']);
                                 $html = " <div class='check' id='{$module}' deps='{$deps}' cons='{$conflicts}' opt='{$optional}'>\n    <input type='checkbox' name='modules[]' value='{$module}' {$checked} id='input_enable_{$module}' />\n  </div>\n";
                                 $origEnableNode->parentNode->replaceChild($this->template->importText($html), $origEnableNode);
                                 $possibles[] = $module;
                             }
                         }
                     }
                 }
             }
             $display = array();
             foreach ($displayData as $name => $dd) {
                 if (isset($data->{$dd})) {
                     $display[$name] = $data->{$dd};
                 } else {
                     $display[$name] = '';
                 }
             }
             if (!empty($display['module_email'])) {
                 if (!(substr($display['module_email'], 0, 6) == 'mailto')) {
                     $display['module_email'] = 'mailto://' . $display['module_email'];
                 }
             }
             $display['module_message'] = '';
             foreach ($display as $name => $val) {
                 $this->template->setDisplayData($name, $val, $modNode);
             }
             $module_menu = 'admin/modules';
             if ($module != 'I2CE') {
                 $module_menu .= '/' . $module;
             }
             $module_configure = '';
             if (!$conflicting && (!isset($data->noConfigData) || $data->noConfigData != 1) && $this->mod_factory->isInitialized($module) && $this->mod_factory->isEnabled('swissConfig')) {
                 $module_configure = 'swissConfig/edit/' . $module;
             }
             $menuLinkNodeList = $this->template->query(".//a[@name='module_menu']", $modNode);
             if ($menuLinkNodeList->length > 0) {
                 $menuLinkNode = $menuLinkNodeList->item(0);
             }
             if ($menuLinkNode instanceof DOMElement) {
                 $menuLinkNode->setAttribute('id', 'menu_link_' . $module);
             }
             if (!isset($data->paths->MODULES) || $this->shortname == $module || $conflicting) {
                 $module_menu = '';
             } else {
                 if ($this->hasAjax() === true) {
                     $subModNode = $this->template->appendFileByName("module_sub_module.html", "li", "module_list", -1);
                     if ($subModNode instanceof DOMElement) {
                         $subModNode->setAttribute('id', "sub_module_li_{$module}");
                     }
                     $subModDiv = $this->template->query("./descendant-or-self::node()[@id='sub_module']", $subModNode);
                     if ($subModDiv->length > 0) {
                         $subModDiv = $subModDiv->item(0);
                     }
                     if ($subModDiv instanceof DOMElement) {
                         $subModDiv->setAttribute('id', "sub_module_{$module}");
                     }
                     $arrowNode = $this->template->createElement('img', array('src' => 'file/admin-arrow-down.gif', 'id' => "menu_link_arrow_{$module}"));
                     $menuLinkNode->parentNode->appendChild($arrowNode);
                     $this->addAjaxUpdate("sub_module_{$module}", "menu_link_arrow_{$module}", 'click', $module_menu, "modules", true);
                     //fuzzy method from stub module
                     $this->addAjaxCompleteFunction("menu_link_arrow_{$module}", "Modules.update(\"{$module}\");");
                     //fuzzy method from stub module
                 }
             }
             $this->template->setDisplayDataImmediate("module_configure", $module_configure, $modNode);
             $this->template->setDisplayDataImmediate("module_menu", $module_menu, $modNode);
         }
     }
     $possibleNode = $this->template->getElementById('module_possibles', $menuNode);
     if ($possibleNode instanceof DOMElement) {
         $possibleNode->setAttribute('value', implode(':', $possibles));
     }
     $formNode = $this->template->getElementByName('admin_enable_form', 0);
     if ($formNode instanceof DOMElement) {
         $action = 'admin/enable';
         if ($this->shortname != 'I2CE') {
             $action .= '/' . $this->shortname;
         }
         $formNode->setAttribute('action', $action);
     }
     I2CE_ModuleFactory::callHooks('post_admin_menu_modules', array('page' => $this, 'possibles' => $possibles));
 }
Esempio n. 10
0
 /**
  * Display the template as HTML/XML.  Sets the header and displays any buffered warnings/echoed text.
  */
 protected function _display($supress_output)
 {
     if (!$supress_output && array_key_exists('HTTP_HOST', $_SERVER)) {
         $headers = $this->template->getHeaders();
         if (!is_array($headers)) {
             $headers = array($headers);
         }
         foreach ($headers as $header) {
             header($header);
         }
     }
     $classes = array();
     if ($this->template instanceof I2CE_TemplateMeister) {
         $class = get_class($this->template);
         while ($class && $class != 'I2CE_Fuzzy') {
             $classes[] = $class;
             $class = get_parent_class($class);
         }
         $num = count($classes);
     }
     I2CE_ModuleFactory::callHooks('pre_page_prepare_display', $this);
     for ($i = $num - 1; $i >= 0; $i--) {
         I2CE_ModuleFactory::callHooks('pre_page_prepare_display_' . $classes[$i], $this);
     }
     if ($this->template instanceof I2CE_TemplateMeister) {
         $this->template->prepareDisplay();
     }
     for ($i = $num - 1; $i >= 0; $i--) {
         I2CE_ModuleFactory::callHooks('post_page_prepare_display_' . $classes[$i], $this);
     }
     I2CE_ModuleFactory::callHooks('post_page_prepare_display', $this);
     if ($this->template instanceof I2CE_Template) {
         $this->template->checkRolesTasksAndPermissions();
     }
     I2CE_ModuleFactory::callHooks('final_page_prepare_display', $this);
     if (!$supress_output) {
         $display = '';
         if ($this->template instanceof I2CE_TemplateMeister) {
             $display = $this->template->getDisplay();
         }
         $buffer = '';
         if (ob_get_level() == I2CE::$ob_level + 1) {
             $buffer = ob_get_clean();
         }
         echo $display;
         flush();
         if ($buffer) {
             I2CE::raiseError("The page " . $_SERVER['PHP_SELF'] . " has errors");
             $buffer = str_replace(array('<br/>', '<br />'), "\n", $buffer);
             $buffer = htmlentities($buffer, ENT_COMPAT, 'UTF-8', false);
             echo "<span class='buffered_errors'><pre>{$buffer}</pre></span>";
         }
     }
 }
 /**
  * Display the recent changes list for the given form.
  * @return boolean
  */
 protected function actionRecent()
 {
     $form = array_shift($this->request_remainder);
     $form_config = I2CE::getConfig()->traverse("/modules/forms/forms");
     if (!$form_config->is_parent($form) || !I2CE::getConfig()->is_parent("/modules/RecentForm/forms/{$form}")) {
         return $this->actionMenu();
     }
     $page_size = 25;
     $days = "today";
     $user = false;
     if (count($this->request_remainder) > 0) {
         $days = array_shift($this->request_remainder);
     }
     $user_list = false;
     if (count($this->request_remainder) > 0) {
         $user_list = array_shift($this->request_remainder);
         $user = explode(',', $user_list);
         foreach ($user as $key => $uid) {
             if ($uid == "me") {
                 $uobj = new I2CE_User();
                 $user[$key] = $uobj->getId();
             }
         }
         $user = array_filter($user, "is_numeric");
         if (count($user) == 0) {
             $user = false;
         } elseif (count($user) == 1) {
             $user = array_pop($user);
         }
     }
     switch ($days) {
         case "yesterday":
             $mod_time = mktime(0, 0, 0, date("n"), date("j") - 1);
             break;
         case "week":
             $mod_time = mktime(0, 0, 0, date("n"), date("j") - 7);
             break;
         default:
             $mod_time = mktime(0, 0, 0);
             break;
     }
     $form_name = $form;
     $form_config->setIfIsSet($form_name, "{$form}/display");
     $user_link = "";
     if ($user_list) {
         $user_link = "/" . $user_list;
     }
     $this->template->setDisplayDataImmediate("display_form_name", ": " . $form_name);
     $header = $this->template->appendFileById("recent_display.html", "div", "recent_forms");
     $this->template->setDisplayDataImmediate("recent_name", $form_name, $header);
     $this->template->setDisplayDataImmediate("recent_date", date("d M Y", $mod_time), $header);
     $this->template->setDisplayDataImmediate("recent_today_link", array("href" => "recent/{$form}/today" . $user_link), $header);
     $this->template->setDisplayDataImmediate("recent_yesterday_link", array("href" => "recent/{$form}/yesterday" . $user_link), $header);
     $this->template->setDisplayDataImmediate("recent_week_link", array("href" => "recent/{$form}/week" . $user_link), $header);
     $this->template->setDisplayDataImmediate("recent_me_link", array("href" => "recent/{$form}/{$days}/me"), $header);
     $this->template->setDisplayDataImmediate("recent_all_link", array("href" => "recent/{$form}/{$days}"), $header);
     $recent_form_config = I2CE::getConfig()->traverse("/modules/RecentForm/forms/{$form}", true);
     $fields = $recent_form_config->fields->getAsArray();
     ksort($fields);
     if (!is_array($fields)) {
         $fields = array();
     }
     $display = implode(" ", array_fill(0, count($fields), "%s"));
     $recent_form_config->setIfIsSet($display, "display");
     $link = "recent";
     $recent_form_config->setIfIsSet($link, "link");
     $parent = false;
     $recent_form_config->setIfIsSet($parent, "parent");
     if ($parent) {
         $parent = true;
     }
     $order = $fields;
     array_unshift($order, "-last_modified");
     if ($this->request_exists("page")) {
         $limit_start = ((int) $this->request("page") - 1) * $page_size;
     } else {
         $limit_start = 0;
     }
     $results = I2CE_FormStorage::listDisplayFields($form, $fields, $parent, array(), $order, array($limit_start, $page_size), $mod_time, false, $user);
     $num_found = I2CE_FormStorage::getLastListCount($form);
     $this->template->setDisplayDataImmediate("recent_found", $num_found, $header);
     foreach ($results as $id => $data) {
         $record = $this->template->appendFileById("recent_display_form.html", "li", "recent_list");
         if ($parent) {
             $this->template->setDisplayDataImmediate("form_link", array("href" => $link . $data['parent']), $record);
         } else {
             $this->template->setDisplayDataImmediate("form_link", array("href" => $link . $form . "|" . $id), $record);
         }
         $extra_display = I2CE_ModuleFactory::callHooks("recent_form_{$form}_display", $data);
         array_unshift($extra_display, vsprintf($display, $data));
         $this->template->setDisplayDataImmediate("record_display", implode(' ', $extra_display), $record);
     }
     if ($this->module == "I2CE") {
         $url = $this->page . "/" . $form . "/" . $days;
     } else {
         $url = $this->module . "/" . $this->page . "/" . $form . "/" . $days;
     }
     $total_pages = max(1, ceil($num_found / $page_size));
     if ($total_pages > 1) {
         $page_num = (int) $this->request('page');
         $page_num = min(max(1, $page_num), $total_pages);
         $this->makeJumper("recent", $page_num, $total_pages, $url, array());
     }
 }
 /**
  * Make sure all the appropriate module limits are available.
  */
 protected function ensureModuleLimits()
 {
     if ($this->ensured) {
         return;
     }
     if ($this->storage->is_scalar()) {
         return false;
     }
     if (!$this->parent instanceof I2CE_Swiss_CustomReports_Report_ReportingForm_Field) {
         return false;
     }
     if (($fieldObj = $this->parent->getFieldObj()) instanceof I2CE_FormField) {
         I2CE::raiseError("Calling get_report_module_limit_options on " . $fieldObj->getHTMLName());
         $limits = I2CE_ModuleFactory::callHooks("get_report_module_limit_options");
         I2CE::raiseError("get_report_module_limit_options returns" . print_r($limits, true));
         foreach ($limits as $limit) {
             if (!is_array($limit) || !array_key_exists('fields', $limit) || !is_array($limit['fields'])) {
                 continue;
             }
             if ($fieldObj->getName() == 'id' && ($formObj = $fieldObj->getContainer()) instanceof I2CE_Form && array_key_exists($form = $formObj->getName(), $limit['fields'])) {
                 $limit['fields'] = array($form => $limit['fields'][$form]);
             } elseif ($fieldObj instanceof I2CE_FormField_MAPPED && count($field_forms = $fieldObj->getSelectableForms()) == 1) {
                 //check to see if the fields mapped value can be one of the selectable form
                 I2CE::raiseError("Have a mapped Field with selectable forms:\n\t" . implode(" ", $field_forms) . "\ncomapring against access_facility+location selectable:\n\t" . implode(" ", array_keys($limit['fields'])));
                 foreach ($limit['fields'] as $form => $formName) {
                     if (!in_array($form, $field_forms)) {
                         unset($limit['fields'][$form]);
                     }
                 }
             } else {
                 $limit['fields'] = array();
             }
             if (count($limit['fields']) == 0) {
                 continue;
             }
             $swissModuleLimit = $this->getChild($limit['module'], true);
             if (!$swissModuleLimit instanceof I2CE_Swiss_CustomReports_Report_ReportingForm_Field_ModuleLimit) {
                 I2CE::raiseError("Bad swiss child for " . $limit['module']);
             }
             $swissModuleLimit->setFieldOptions($limit['fields']);
             $this->allowed[] = $limit['module'];
         }
     }
     $this->ensured = true;
 }
Esempio n. 13
0
 /**
  * Validates and sets the preferred locales for the session
  * in order of decreasing preference.  It makes sure that self::DEFAULT_LOCALE is in the list
  * of preferred locales.
  * @param mixed @locales. string or array of  string.  The preferred locale or an array of prefered locales.
  * @returns array of string, the locales that were set.
  */
 protected static function setPreferredLocales($locales)
 {
     $old_locales = self::getPreferredLocales();
     $changed = false;
     if (!array_key_exists('preferred_locales', $_SESSION) || !is_array($_SESSION['preferred_locales'])) {
         $changed = true;
     } else {
         if (count($_SESSION['preferred_locales']) != count($locales)) {
             $changed = true;
         } else {
             foreach ($locales as $i => $locale) {
                 if ($locale != $_SESSION['preferred_locales'][$i]) {
                     $changed = true;
                     break;
                 }
             }
         }
     }
     I2CE::getConfig()->setLocales($locales);
     if ($changed) {
         $_SESSION['preferred_locales'] = $locales;
         I2CE_ModuleFactory::callHooks('locales_changed', array('old_locales' => $old_locales, 'locales' => $locales));
     }
     return $_SESSION['preferred_locales'];
 }
Esempio n. 14
0
 /**
  * Clean up all the fields for this form.
  * 
  * This will unset all the fields associated with this form.  This will remove
  * all circular references to this form so it can be cleaned up by the garbage collector.
  * This should only be called when the form is no longer needed.  Trying to access it
  * after this may cause unexpected results or errors.
  */
 public function cleanup($remove_from_cache = true)
 {
     if ($this->parentField instanceof I2CE_FormField) {
         $this->parentField->cleanup();
     }
     unset($this->parentField);
     if ($this->lastModifiedField instanceof I2CE_FormField) {
         $this->lastModifiedField->cleanup();
     }
     if ($this->createdField instanceof I2CE_FormField) {
         $this->createdField->cleanup();
     }
     unset($this->lastModifiedField);
     unset($this->createdField);
     I2CE_ModuleFactory::callHooks('form_cleanup', array('form' => $this, 'remove_from_cache' => $remove_from_cache));
     parent::cleanup($remove_from_cache);
 }
Esempio n. 15
0
 /**
  * Perform the actions of the page.
  */
 protected function action()
 {
     $can_see = false;
     if ($this->hasPermission('task(users_can_edit_all)')) {
         $can_see = true;
     } elseif ($this->hasPermission('task(users_can_edit)')) {
         $userAccess = I2CE::getUserAccess();
         if ($userAccess instanceof I2CE_UserAccess_Mechansim && in_array('creator', $userAccess->getAllowedDetails()) && $this->view_user->creator == $this->user->id) {
             $can_see = true;
         }
     }
     if (!$can_see) {
         $this->userMessage("You can not edit this user.", 'notice', false);
         $this->setRedirect("user");
         return false;
     }
     I2CE_ModuleFactory::callHooks("pre_page_view_user", $this);
     parent::action();
     $this->template->setForm($this->view_user);
     $child_forms = $this->view_user->getChildForms();
     foreach ($child_forms as $child) {
         $method = "action_" . $child;
         if ($this->_hasMethod($method)) {
             if (!$this->{$method}()) {
                 I2CE::raiseError("Could not do action for {$form}.");
             }
         }
     }
     I2CE_ModuleFactory::callHooks("post_page_view_user", $this);
     return true;
 }
Esempio n. 16
0
 /**
  * Delete a form object.
  * @param I2CE_Form $form
  * @param  boolean $transact a flag to use transactions or not. default: true
  * @param boolean $no_history a flag to determine if the record should not go to the deleted_records
  *                             table. default: false
  * @return boolean
  */
 public function delete($form, $transact = true, $no_history = false)
 {
     $storageMechanism = self::getStorageMechanism($form);
     if (!$storageMechanism) {
         return false;
     }
     if ($form->getId() == '0' || $form->getId() == '') {
         return false;
     }
     if (!$this->isWritable($form)) {
         return true;
     }
     if (!$no_history && !$form->storeHistory()) {
         I2CE::raiseError("Could not store form hustory");
         return false;
     }
     I2CE_ModuleFactory::callHooks("form_pre_delete", array('form' => $form));
     $delete_result = $storageMechanism->delete($form, $transact);
     I2CE_ModuleFactory::callHooks("form_post_delete", array('form' => $form));
     return $delete_result;
 }
 /**
  * Update the position for this to mark it as closed and then save the object.
  */
 public function save()
 {
     $this->position->save($this->user);
     if (($personPosition = $this->getPrimary()) instanceof iHRIS_PersonPosition) {
         I2CE_ModuleFactory::callHooks("depart_position_save", $personPosition);
     }
     parent::save();
 }
    /**
     * Run the appropriate cron jobs based on the cron type.
     * @param string $type
     */
    public function cronjob($type)
    {
        // We need to run any normal hooks and not CLI hooks for this process if run from CLI
        $host_changed = false;
        if (!array_key_exists('HTTP_HOST', $_SERVER)) {
            $host_changed = true;
            $_SERVER['HTTP_HOST'] = '';
        }
        // Find all the Module Access modules that are available so the user can be set.
        $report_limits = I2CE_ModuleFactory::callHooks("get_report_module_limit_options");
        $limit_modules = array();
        foreach ($report_limits as $limit) {
            if (array_key_exists('module', $limit)) {
                $mod = I2CE_ModuleFactory::instance()->getClass($limit['module']);
                $limit_modules[] = array('module' => $mod, 'user' => $mod->getUser());
            }
        }
        $cron_type_where = array('operator' => "FIELD_LIMIT", 'style' => 'equals', 'field' => 'cron_type', 'data' => array('value' => $type));
        $reports = I2CE_FormStorage::listFields('cron_report', array('parent', 'report_view'), false, $cron_type_where);
        foreach ($reports as $report) {
            $view = $report['report_view'];
            $user = I2CE_FormFactory::instance()->createContainer($report['parent']);
            // Set the user on all access modules to limit results.
            foreach ($limit_modules as $module) {
                $module['module']->setUser($user->user);
            }
            $_SESSION['user_name'] = $user->username;
            $page = new I2CE_Page_ShowReport(array(), array($view));
            $template = $page->getTemplate();
            $display = $page->getDesiredDisplays($view);
            $use_display = 'Default';
            if ($display[0] != 'PieChart') {
                $use_display = $display[0];
            }
            $displayObj = $page->instantiateDisplay($use_display, $view);
            $config = I2CE::getConfig()->modules->CustomReports->reportViews->{$view};
            $template->loadRootText("<span id='siteContent' />");
            $contentNode = $template->getElementById('siteContent');
            $attachments = array();
            $report_name = $config->display_name;
            $report_desc = $config->description;
            $report_limit = '';
            $generated = strftime('%c');
            switch ($use_display) {
                case "CrossTab":
                    if ($displayObj->isExport()) {
                        $export = $displayObj->generateExport($contentNode, false);
                        $html = false;
                        $attachments[] = array('type' => "text/csv; charset=UTF-8", 'data' => $export, 'name' => $this->getFileName($report_name) . ".csv");
                        break;
                    }
                    // If not export then fall through to the Default
                // If not export then fall through to the Default
                case "Default":
                    $displayObj->unsetPaging();
                    $displayObj->display($contentNode);
                    $report_limit = $displayObj->getReportLimitsDescription();
                    $css = I2CE::getFileSearch()->search('CSS', 'customReports_display_Default.css');
                    $report_css = file_get_contents($css);
                    $report_table = $template->getElementById('report_table');
                    $report_content = $template->doc->saveHTML($report_table);
                    $html = <<<EOF
<?xml version="1.0" encoding="utf-8"?>'
<!DOCTYPE html>
<html>
<head>
    <title>Automated Report: {$report_name}</title>
    <style type="text/css">
{$report_css}
    </style>
</head>
<body>
    <h1>{$report_name}</h1>
    <h2>{$report_desc}</h2>
    <h3>{$report_limit}</h3>
    <p>Generated on: {$generated}</p>
    {$report_content}
</body>
</html>
EOF;
                    break;
                case "PDF":
                    $pdf = $displayObj->getPDF($contentNode);
                    $pdf_data = $pdf->Output($report_name, 'S');
                    $html = false;
                    $attachments[] = array('type' => 'application/pdf', 'data' => $pdf_data, 'name' => $this->getFileName($report_name) . ".pdf");
                    break;
                case "Export":
                    $export = $displayObj->generateExport();
                    $html = false;
                    $attachments[] = array('type' => $displayObj->getContentType(true), 'data' => $export, 'name' => $displayObj->getFileName());
                    break;
                default:
                    I2CE::raiseError("Unknown display type used for report display for user cron reports.");
                    break;
            }
            $email = $user->email;
            // This is duplicated from the Default setting so it can be in the main mail message as well.
            // It isn't called earlier to avoid duplicate processing with the Default display.
            if (!$html && $report_limit == '') {
                $report_limit = $displayObj->getReportLimitsDescription();
            }
            $mail_msg = wordwrap("This is the automated report for {$report_name}:  {$report_desc}.\nLimits are: {$report_limit}\nGenerated on: {$generated}.");
            if (I2CE_Mailer::mail($email, array('Subject' => 'Automated Report: ' . $report_name), $mail_msg, $html, $attachments)) {
                echo "Report mail {$report_name} (" . $report['report_view'] . ") sent to {$email}.\n";
            } else {
                echo "Report mail {$report_name} (" . $report['report_view'] . ") failed to {$email}.\n";
            }
            //$page->actionCommandLine( array(), array() );
        }
        if ($host_changed) {
            unset($_SERVER['HTTP_HOST']);
        }
        unset($_SESSION['user_name']);
        foreach ($limit_modules as $module) {
            $module['module']->setUser($module['user']);
        }
    }
 /**
  * Save the current row for the given key
  * @param string $key
  * @return boolean
  */
 protected function saveRow($key)
 {
     if (!$this->current[$key]['row']['Firstname'] && !$this->current[$key]['row']['Surname']) {
         $this->userMessage("Unable to add people without names.");
         return false;
     }
     $created = false;
     $district = $this->lookupList("district", $this->current[$key]['row']['Home District']);
     $job = $this->lookupList("job", $this->current[$key]['row']['Position'], 'title');
     $facility = $this->lookupList("health_facility", $this->current[$key]['row']['Facility Name']);
     $council = $this->lookupList("council", $this->current[$key]['row']['Registration Council']);
     $gender = false;
     if (strtolower($this->current[$key]['row']['Gender'][0]) == 'm') {
         $gender = "gender|M";
     } elseif (strtolower($this->current[$key]['row']['Gender'][0]) == 'f') {
         $gender = "gender|F";
     }
     $person_id = false;
     if ($council && $this->current[$key]['row']['Registration Number']) {
         $find_reg = array('operator' => 'AND', 'operand' => array(0 => array('operator' => 'FIELD_LIMIT', 'style' => 'lowerequals', 'field' => 'registration_number', 'data' => array('value' => $this->current[$key]['row']['Registration Number'])), 1 => array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => 'council', 'data' => array('value' => $council))));
         $reg_id = I2CE_FormStorage::search("registration", false, $find_reg, array(), true);
         if ($reg_id) {
             $reg = $this->factory->createContainer("registration|{$reg_id}");
             $reg->populate();
             $person_id = $reg->getParent();
         }
     }
     if (!$person_id) {
         $find_pers = array('operator' => 'AND', 'operand' => array(0 => array('operator' => 'FIELD_LIMIT', 'style' => 'lowerequals', 'field' => 'firstname', 'data' => array('value' => $this->current[$key]['row']['Firstname'])), 1 => array('operator' => 'FIELD_LIMIT', 'style' => 'lowerequals', 'field' => 'surname', 'data' => array('value' => $this->current[$key]['row']['Surname'])), 2 => array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => 'residence', 'data' => array('value' => $district))));
         $person_id = I2CE_FormStorage::search("person", false, $find_pers, array(), true);
         if ($person_id) {
             $person_id = "person|" . $person_id;
         }
     }
     if (!$person_id) {
         $created = true;
         $person = $this->factory->createContainer("person");
         $person->surname = $this->current[$key]['row']['Surname'];
         $person->firstname = $this->current[$key]['row']['Firstname'];
         $person->getField('residence')->setFromDB($district);
         if (!$person->save($this->user)) {
             I2CE::raiseError("Unable to save person for provider upload.");
             return false;
         }
         $person_id = $person->getNameID();
         if ($gender) {
             $demographic = $this->factory->createContainer("demographic");
             $demographic->getField("gender")->setFromDB($gender);
             $demographic->setParent($person_id);
             $demographic->save($this->user);
             $demographic->cleanup();
             unset($demographic);
         }
         if ($job || $facility) {
             $position = $this->factory->createContainer("position");
             $position->getField('health_facility')->setFromDB($facility);
             $position->getField('job')->setFromDB($job);
             $position->setParent($person_id);
             $position->save($this->user);
             $position->cleanup();
             unset($position);
         }
         if ($council && $this->current[$key]['row']['Registration Number']) {
             $registration = $this->factory->createContainer("registration");
             $registration->getField("council")->setFromDB($council);
             $registration->registration_number = $this->current[$key]['row']['Registration Number'];
             $registration->setParent($person_id);
             $registration->save($this->user);
             $registration->cleanup();
             unset($registration);
         }
         if ($this->current[$key]['row']['Tel'] || $this->current[$key]['row']['Email']) {
             $contact = $this->factory->createContainer("person_contact_work");
             $contact->telephone = $this->current[$key]['row']['Tel'];
             $contact->email = $this->current[$key]['row']['Email'];
             $contact->setParent($person_id);
             $contact->save($this->user);
             $contact->cleanup();
             unset($contact);
         }
     }
     if (!$person_id) {
         $this->userMessage("Unable to find or add person " . $this->current[$key]['row']['Firstname'] . " " . $this->current[$key]['row']['Surname']);
     } else {
         $find_inst = array('operator' => 'FIELD_LIMIT', 'style' => 'equals', 'field' => 'provider_instance', 'data' => array('value' => $this->instance->getNameID()));
         $inst_id = I2CE_FormStorage::search("person_instance", $person_id, $find_inst, array(), true);
         if ($inst_id) {
             $pers_instance = $this->factory->createContainer("person_instance|{$inst_id}");
             $pers_instance->populate();
         } else {
             $pers_instance = $this->factory->createContainer("person_instance");
             $pers_instance->setParent($person_id);
             $pers_instance->getField("provider_instance")->setFromDB($this->instance->getNameId());
         }
         $pers_instance->attending = 1;
         if (!$pers_instance->save($this->user)) {
             I2CE::raiseError("Unable to save child form for person_instance");
             return false;
         }
         $pers_instance->cleanup();
         unset($pers_instance);
     }
     I2CE_ModuleFactory::callHooks("upload_participants_" . $key . "_post_save_row", array('created' => $created, 'person' => $person_id, 'data' => $this->current[$key]['row']));
     return true;
 }
Esempio n. 20
0
 /**
  * Saves the user to the database.
  * 
  * This method saves all the user data and updates the access the user has for this system.
  * @global array
  */
 public function save($user, $transact = true)
 {
     I2CE_ModuleFactory::callHooks("form_pre_save", array('form' => $this, 'user' => $user));
     foreach ($this->allowedDetails as $detail) {
         if (!array_key_exists($detail, $this->fields)) {
             I2CE::raiseError("For " . $this->getFormID() . ", trying to access field {$detail} which is not in class " . get_class($this) . "\nAvail = " . implode(" ", array_keys($this->fields)));
             continue;
         }
         $this->user->{$detail} = $this->fields[$detail]->getValue();
     }
     $this->user->username = $this->username;
     list($junk, $role) = $this->fields['role']->getValue();
     $this->user->setRole($role);
     if (!$this->user->save($this->password)) {
         return false;
     }
     I2CE_ModuleFactory::callHooks("form_post_save", array('form' => $this, 'user' => $user));
     return true;
 }
Esempio n. 21
0
 /**
  * The business method if this page is called from the commmand line
  * @param array $request_remainder the remainder of the request after the page specfication.  
  * @param array $args the array of unix style command line arguments 
  */
 protected function actionCommandLine($args, $request_remainder)
 {
     $silent = false;
     if ($this->cli->hasValue('silent')) {
         if (strtolower($this->cli->getValue('silent')) == 'true') {
             $silent = true;
         }
     }
     $type = 'all';
     if ($this->cli->hasValue('type')) {
         $type = $this->cli->getValue('type');
     }
     if ($type != 'all' && !array_key_exists($type, $this->types)) {
         $this->cli->usage("An invalid type was given:  {$type}.\n");
     }
     if ($type != 'all') {
         $list = array($type => $this->types[$type]);
     } else {
         $list = $this->types;
     }
     $this->config->times->volatile(true);
     $this->config->status->volatile(true);
     $this->config->pid->volatile(true);
     foreach ($list as $cron_type => $cron_data) {
         $now = time();
         $run_it = false;
         $last_run = 0;
         $this->config->setIfIsSet($last_run, "times/{$cron_type}");
         if ($last_run == 0) {
             $duration = 0;
             $run_it = true;
         } else {
             $duration = $now - $last_run;
             if (array_key_exists('getdate_key', $cron_data)) {
                 $last_run_time = getdate($last_run);
                 $current_time = getdate($now);
                 if (array_key_exists('getdate_value', $cron_data)) {
                     if ($current_time[$cron_data['getdate_key']] == $cron_data['getdate_value'] && (array_key_exists('delay', $cron_data) ? $duration > $cron_data['delay'] : true)) {
                         $run_it = true;
                     }
                 } else {
                     if ($current_time[$cron_data['getdate_key']] > $last_run_time[$cron_data['getdate_key']]) {
                         $run_it = true;
                     } elseif (array_key_exists('getdate_trail', $cron_data)) {
                         $trail = explode(',', $cron_data['getdate_trail']);
                         foreach ($trail as $key) {
                             if (array_key_exists($key, $last_run_time) && $current_time[$key] > $last_run_time[$key]) {
                                 $run_it = true;
                                 break;
                             }
                         }
                     }
                     if ($run_it && array_key_exists('delay', $cron_data) && $duration < $cron_data['delay']) {
                         $run_it = false;
                     }
                 }
             } elseif (array_key_exists('delay', $cron_data)) {
                 if ($duration > $cron_data['delay']) {
                     $run_it = true;
                 }
             }
         }
         $timeout = 0;
         if (array_key_exists('timeout', $cron_data)) {
             $timeout = $cron_data['timeout'];
         }
         $status = 'done';
         $this->config->setIfIsSet($status, "status/{$cron_type}");
         if ($status == 'in_progress') {
             $pid = 0;
             $this->config->setIfIsSet($pid, "pid/{$cron_type}");
             // Seeing if the current process is still running.
             $pid = (int) $pid;
             $can_kill = 0;
             if ($pid && is_int($pid)) {
                 exec("ps h -o command -p " . escapeshellarg($pid), $output, $ret_val);
                 if ($ret_val == 0 && array_key_exists(0, $output) && strpos($output[0], "--page=/admin/cron") !== false) {
                     $can_kill = $pid;
                     if (!$silent) {
                         echo "Current process is still running so double the timeout.\n";
                     }
                     // Double the timeout or set it to something if it was 0 and the process is still running.
                     $timeout = $timeout * 2;
                     if ($timeout == 0) {
                         $timeout = 86400;
                     }
                 }
             } else {
                 if (!$silent) {
                     echo "Invalid previous pid ({$pid}) so not searching for it.\n";
                 }
             }
             if ($duration < $timeout) {
                 $run_it = false;
             } else {
                 if (!$silent) {
                     echo "Duration exceeds timeout ({$duration} > {$timeout}) so running again.\n";
                 }
                 if ($can_kill) {
                     // Try to kill the running process
                     exec("kill -9 " . escapeshellarg($can_kill));
                     if (!$silent) {
                         echo "Tried to kill existing process {$can_kill}\n";
                     }
                 }
             }
         }
         if ($run_it) {
             $this->config->status->{$cron_type} = 'in_progress';
             $this->config->pid->{$cron_type} = getmypid();
             $this->config->times->{$cron_type} = time();
             I2CE_ModuleFactory::callHooks("cronjob_{$cron_type}");
             $this->config->status->{$cron_type} = 'done';
         } else {
             if (!$silent) {
                 echo "Not time to run {$cron_type} ({$duration}) " . strftime("%c %z", $last_run) . "\n";
             }
         }
     }
 }
 protected function actionGenerate($force)
 {
     /* Why not allow multiple reports to generate at once?
        if (count($this->request_remainder) > 1 ) {
            I2CE::raiseError("Requested generation of invalid report " . implode('/', $this->request_remainder));
            return false;
        }
        */
     if (count($this->request_remainder) == 0) {
         $config = I2CE::getConfig()->modules->CustomReports;
         $config->generate_all->volatile(true);
         $timeConfig = I2CE::getConfig()->traverse('/modules/CustomReports/times', true);
         $timeConfig->volatile(true);
         $fail_time = null;
         $timeConfig->setIfIsSet($fail_time, 'fail');
         if (!is_integer($fail_time)) {
             $fail_time = 600;
         }
         $fail_time = (int) ((int) $fail_time * 60);
         $generation = 0;
         $timeConfig->setIfIsSet($generation, "generate_all/time");
         if (!(is_integer($generation) || ctype_digit($generation)) || (int) $generation < 1) {
             $generation = 0;
         }
         $generation = (int) $generation;
         $config->setIfIsSet($status, 'generate_all/status');
         if ($status === 'in_progress' && (!$force || time() - $generation < $fail_time)) {
             I2CE::raiseError("In progress");
             return true;
         }
         $config->generate_all->status = 'in_progress';
         $config->generate_all->time = time();
         //update the time
         $reports = I2CE::getConfig()->modules->CustomReports->reports->getKeys();
         $all = true;
     } else {
         $reports = $this->request_remainder;
         $all = false;
     }
     //         //generate caches.
     //         $wrangler = new I2CE_Wrangler();
     //         $cachedFormPage = $wrangler->getPage('CachedForms','cacheAll');
     //         if ($cachedFormPage instanceof I2CE_Page) {
     //             $cachedFormPage->cacheAll();
     //         }
     $errors = array();
     foreach ($reports as $report) {
         if (!I2CE_CustomReport::reportExists($report)) {
             I2CE::raiseError("Requested generation of report {$report} which does not exist");
             $errors[] = "Requested generation of report {$report} which does not exist";
             continue;
         }
         try {
             $reportObj = new I2CE_CustomReport($report);
         } catch (Exception $e) {
             $errors[] = "Could not instantiate the report {$report}";
             continue;
         }
         if (!$reportObj->generateCache($force)) {
             $errors[] = "Could not generate report for {$report}";
         }
     }
     if ($all) {
         $hook_errs = I2CE_ModuleFactory::callHooks('custom_reports_post_generate_all', $force);
         foreach ($hook_errs as $hook_err) {
             if ($hook_err && $hook_err !== true) {
                 if (is_string($hook_err) && strlen($hook_err) > 0) {
                     $errors[] = $hook_err;
                 } else {
                     $errors[] = "An unknown error occurred trying to run post custom report generation hook.";
                 }
             }
         }
         if (count($errors) > 0) {
             $config->generate_all->status = 'failed';
         } else {
             $config->generate_all->status = 'done';
         }
         $config->generate_all->time = time();
     }
     foreach ($errors as $error) {
         $this->userMessage($error, 'notice');
     }
     return count($errors) == 0;
 }
 /**
  * Update the position for this to mark it as closed and then save the object.
  */
 public function save()
 {
     if (!$this->hasPermission('task(person_can_edit_child_form_person_position)')) {
         $this->userMessage("You can't change a person's position");
         return false;
     }
     $new_person_position = $this->getPrimary();
     if ($this->post_exists('position_option') && $this->post('position_option') == 'create' && $this->new_position instanceof iHRIS_Position) {
         $this->new_position->setStatus("position_status|closed");
         $this->new_position->save($this->user);
         $new_person_position->getField("position")->setFromDB($this->new_position->getNameId());
         $position = $this->new_position;
     } else {
         $position = $this->factory->createContainer($new_person_position->getField("position")->getDBValue());
         $position->statusOnly();
         $position->closePosition($this->user, $this->getParent()->getId());
     }
     if ($this->getParent()->isActive() && $this->old_position instanceof iHRIS_Position) {
         $this->old_position->statusOnly();
         $this->old_position->save($this->user);
         $person = $this->getParent();
         if ($this->old_person_position instanceof iHRIS_PersonPosition) {
             $this->old_person_position->end_date = $new_person_position->start_date;
             $this->old_person_position->save($this->user);
             I2CE_ModuleFactory::callHooks("make_promotion_save", $this->old_person_position, $new_person_position);
         }
         //$this->getPrimary()->reason = null;
     }
     I2CE_ModuleFactory::callHooks("make_offer_save", $new_person_position);
     foreach ($this->objects[self::EDIT_CHILD] as $obj) {
         if ($obj->getId() == '0') {
             $obj->setParent($new_person_position);
         }
         I2CE_ModuleFactory::callHooks("make_offer_save_" . $obj->getName(), $new_person_position, $obj);
     }
     parent::save();
 }
 /**
  * Perform the main actions of the page.
  */
 protected function action()
 {
     $task = $this->getViewChildTask();
     if (I2CE_PermissionParser::taskExists($task) && !$this->hasPermission("task({$task})")) {
         $this->userMessage("You do not have permission to view this {$childForm}", true);
         return false;
     }
     $tag = array_key_exists('template_tag', $this->args) && is_scalar($this->args['template_tag']) ? $this->args['template_tag'] : 'div';
     $append_id = array_key_exists('template_id', $this->args) && is_scalar($this->args['template_id']) ? $this->args['template_id'] : 'child_form';
     $appendNode = $this->template->getElementById($append_id);
     if (!$appendNode instanceof DOMNode) {
         I2CE::raiseError("No {$append_id} to add child form " . $this->childForm);
         return false;
     }
     $limit_page = $this->request_exists('limit_page') ? $this->request('limit_page') : 1;
     if ($limit_page < 1) {
         $limit_page = 1;
     }
     $order_by = $this->getOrderBy();
     $found = I2CE_FormStorage::search($this->childForm, $this->parent->getNameId(), array(), $order_by, array($limit_page - 1, 1));
     if (!$found && $limit_page > 1) {
         $limit_page = 1;
         $found = I2CE_FormStorage::search($this->childForm, $this->parent->getNameId(), array(), $order_by, array($limit_page - 1, 1));
     }
     if (!$found) {
         $this->redirect("view?id=" . $this->parent->getNameId());
         return true;
     }
     $total_rows = I2CE_FormStorage::getLastListCount($this->childForm);
     if ($total_rows <= 1) {
         $this->template->setAttribute('style', 'display:none;', 'child_pager_div');
     } else {
         $query = $this->request();
         unset($query['limit_page']);
         $query = I2CE_Page::flattenRequestVars($query);
         $this->makeScalingJumper('child', $limit_page, $total_rows, $this->pageRoot(), $query, 'limit_page');
     }
     $this->child = I2CE_FormFactory::instance()->createContainer($this->childForm . "|" . $found);
     $this->child->populate();
     I2CE_ModuleFactory::callHooks('pre_add_child_form_' . $this->childForm, array('form' => $this->child, 'page' => $this, 'set_on_node' => null, 'append_node' => $appendNode));
     $childNode = $this->template->appendFileByNode($this->getViewChildTemplate(), $tag, $appendNode);
     $this->template->setForm($this->child, $childNode);
     I2CE_ModuleFactory::callHooks('post_add_child_form_' . $this->childForm, array('form' => $this->child, 'page' => $this, 'node' => $childNode, 'set_on_node' => null, 'append_node' => $appendNode));
     $this->template->setDisplayDataImmediate("child_form_header", "View " . $this->child->getDisplayName());
     if (array_key_exists('show_edit', $this->args) ? !$this->args['show_edit'] : true) {
         $this->template->findAndRemoveNodes("//div[@class='editRecord']");
     }
     // Do we want this?
     // $this->template->findAndRemoveNodes( "//span[@history='false']" );
     return true;
 }
 /**
  * Hander for hook triggers
  * @param string $username The username to be notified
  * @param string $trigger The trigger being called
  * @param string $message The message to send
  * @param string $link The optional link to include
  * @param string $link_text The link text for the link
  * @param array $args Any option arguments for this trigger handler
  * @return boolean
  */
 public function triggerHook($username, $trigger, $message, $link = false, $link_text = '', $args = array())
 {
     if (!array_key_exists('hooks', $args)) {
         I2CE::raiseError("No hooks defined for {$trigger}.  It must be defined in /modules/UserTriggers/triggers/{$trigger}/args/hok/hooks");
         return false;
     }
     $hooks = $args['hooks'];
     if (!is_array($hooks)) {
         $hooks = array($hooks);
     }
     foreach ($hooks as $hook) {
         I2CE_ModuleFactory::callHooks($hook, $username, $trigger, $message, $link, $link_text, $args);
     }
 }
 /**
  * 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 templateData($page)
 {
     if (!$page instanceof I2CE_Page) {
         I2CE::raiseError("Did not get expected page");
         return;
     }
     if (!$page->getTemplate() instanceof I2CE_TemplateMeister) {
         I2CE::raiseError("Did not get expected template");
         return;
     }
     $types = array();
     foreach ($this->data as $counter => $data) {
         foreach (array_keys($data) as $type) {
             $types[$type] = true;
         }
     }
     $prioritized_list = array();
     $unprioritized_list = array();
     foreach (array_keys($types) as $type) {
         if (isset($this->data_priorities[$type])) {
             $prioritized_list[$this->data_priorities[$type]][] = $type;
         } else {
             $unprioritized_list[] = $type;
         }
     }
     ksort($prioritized_list);
     array_push($prioritized_list, $unprioritized_list);
     $this->processPostponed($page->getTemplate());
     foreach ($prioritized_list as $types) {
         foreach ($types as $type) {
             I2CE_ModuleFactory::callHooks("process_templatedata_{$type}", $page);
         }
     }
 }