Example #1
0
 function _loadActionsINIFile()
 {
     import('Dataface/ConfigTool.php');
     $configTool =& Dataface_ConfigTool::getInstance();
     $actions =& $configTool->loadConfig('actions', null);
     foreach (array_keys($actions) as $key) {
         $action =& $actions[$key];
         $action['name'] = $key;
         if (!isset($action['id'])) {
             $action['id'] = $action['name'];
         }
         if (!isset($action['label'])) {
             $action['label'] = str_replace('_', ' ', ucfirst($action['name']));
         }
         if (!isset($action['accessKey'])) {
             $action['accessKey'] = substr($action['name'], 0, 1);
         }
         //if ( !isset($action['label_i18n']) ) $action['label_i18n'] = 'action:'.$action['name'].' label';
         //if ( !isset($action['description_i18n'])) $action['description_i18n'] = 'action:'.$action['name'].' description';
         if (isset($action['description'])) {
             $action['description'] = df_translate('actions.' . $action['name'] . '.description', $action['description']);
         }
         if (isset($action['label'])) {
             $action['label'] = df_translate('actions.' . $action['name'] . '.label', $action['label']);
         }
         $this->actions[$key] =& $action;
         unset($action);
     }
     unset($temp);
     $this->actions =& $actions;
 }
Example #2
0
 function &pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $element->getName();
     $val = $element->getValue();
     //print_r($val);exit;
     if (is_array($val)) {
         $val = $val[$field['name']];
     }
     if (preg_match('/int/', @$field['Type']) and $val !== '' and $val !== null) {
         //print_r($_POST);
         //echo "Val is $val";exit;
         $out = intval($val);
     } else {
         //echo "Out is $val";exit;
         $out = $val;
     }
     //$res =& $s->setValue($fieldname, $val);
     if (PEAR::isError($val)) {
         $val->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_PUSHING_VALUE', "Error pushing value for field '{$field['name']}' in QuickForm::pushWidget() on line " . __LINE__ . " of file " . __FILE__, array('name' => $field['name'], 'file' => __FILE__, 'line' => __LINE__)));
         return $val;
     }
     return $out;
 }
Example #3
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $this->table =& Dataface_Table::loadTable($query['-table']);
     $translations =& $this->table->getTranslations();
     foreach (array_keys($translations) as $trans) {
         $this->table->getTranslation($trans);
     }
     //print_r($translations);
     if (!isset($translations) || count($translations) < 2) {
         // there are no translations to be made
         trigger_error('Attempt to translate a record in a table "' . $this->table->tablename . '" that contains no translations.', E_USER_ERROR);
     }
     $this->translatableLanguages = array_keys($translations);
     $translatableLanguages =& $this->translatableLanguages;
     $this->languageCodes = new I18Nv2_Language($app->_conf['lang']);
     $languageCodes =& $this->languageCodes;
     $currentLanguage = $languageCodes->getName($app->_conf['lang']);
     if (count($translatableLanguages) < 2) {
         return PEAR::raiseError(df_translate('Not enough languages to translate', 'There aren\'t enough languages available to translate.'), DATAFACE_E_ERROR);
     }
     //$defaultSource = $translatableLanguages[0];
     //$defaultDest = $translatableLanguages[1];
     $options = array();
     foreach ($translatableLanguages as $lang) {
         $options[$lang] = $languageCodes->getName($lang);
     }
     unset($options[$app->_conf['default_language']]);
     $tt = new Dataface_TranslationTool();
     $form = new HTML_QuickForm('StatusForm', 'POST');
     $form->addElement('select', '--language', 'Translation', $options);
     $form->addElement('select', '--status', 'Status', $tt->translation_status_codes);
     //$form->setDefaults( array('-sourceLanguage'=>$defaultSource, '-destinationLanguage'=>$defaultDest));
     $form->addElement('submit', '--set_status', 'Set Status');
     foreach ($query as $key => $value) {
         $form->addElement('hidden', $key);
         $form->setDefaults(array($key => $value));
     }
     if ($form->validate()) {
         $res = $form->process(array(&$this, 'processForm'));
         if (PEAR::isError($res)) {
             return $res;
         } else {
             header('Location: ' . $app->url('-action=list&-sourceLanguage=&-destinationLanguage=&-translate=') . '&--msg=' . urlencode('Translation status successfully set.'));
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $records =& $this->getRecords();
     df_display(array('form' => $out, 'translationTool' => &$tt, 'records' => &$records, 'translations' => &$options, 'context' => &$this), 'Dataface_set_translation_status.html');
 }
Example #4
0
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     $record_id = @$_POST['--record_id'];
     try {
         if (!$record_id) {
             throw new Exception(df_translate('Bad Request', 'Bad Request.  Missing parameter.'), self::BAD_REQUEST);
         }
         $record = df_get_record_by_id($record_id);
         if (PEAR::isError($record)) {
             error_log($record->getMessage());
             throw new Exception(df_translate('Bad Request', 'Bad Request - invalid ID.'), self::BAD_REQUEST);
         }
         if (!$record) {
             throw new Exception(df_translate('No records matched request', 'No records matched the request'), self::NOT_FOUND);
         }
         if (!$record->checkPermission('delete')) {
             throw new Exception(df_translate('scripts.GLOBAL.MESSAGE.PERMISSION_DENIED', 'Permission Denied'), self::PERMISSION_DENIED);
         }
         $res = $record->delete(false);
         // We've already done a security check...
         if (PEAR::isError($res)) {
             error_log($res->getMessage());
             throw new Exception(df_translate('actions.rest_delete.messages.SERVER_ERROR', 'Failed to delete record due to a server error.  See error log for details.'), self::SERVER_ERROR);
         }
         $this->out(array('code' => 200, 'message' => df_translate('actions.rest_delete.messages.SUCCESS', 'Successfully deleted record.'), 'record_id' => $record->getId()));
         exit;
     } catch (Exception $ex) {
         switch ($ex->getCode()) {
             case self::PERMISSION_DENIED:
             case self::NOT_FOUND:
             case self::SERVER_ERROR:
                 $msg = $ex->getMessage();
                 $code = $ex->getCode();
                 break;
             default:
                 $msg = df_translate('actions.rest_delete.messages.SUCCESS', 'Successfully deleted record.');
                 $code = self::SERVER_ERROR;
                 error_log($ex->getMessage());
                 break;
         }
         $this->out(array('code' => $code, 'message' => $msg));
         exit;
     }
 }
Example #5
0
 function handle($params)
 {
     if (!isset($params['action']['page'])) {
         trigger_error(df_translate('Page not specified', 'No page specified at ' . Dataface_Error::printStackTrace(), array('stack_trace' => Dataface_Error::printStackTrace())), E_USER_ERROR);
     } else {
         $page = $params['action']['page'];
     }
     $app =& Dataface_Application::getInstance();
     $pages = $app->getCustomPages();
     if (!isset($pages[$page])) {
         trigger_error(df_translate('Custom page not found', "Request for custom page '{$page}' failed because page does not exist in pages directory." . Dataface_Error::printStackTrace(), array('page' => $page, 'stack_trace' => Dataface_Error::printStackTrace())), E_USER_ERROR);
     }
     ob_start();
     include $pages[$page];
     $out = ob_get_contents();
     ob_end_clean();
     df_display(array('content' => $out), 'Dataface_Custom_Template.html');
     return true;
 }
Example #6
0
 /**
  * Loads a module and returns a reference to it.
  * @param string $name The name of the module's class.
  *
  */
 function &loadModule($name)
 {
     $app =& Dataface_Application::getInstance();
     if (isset($this->_modules[$name])) {
         return $this->_modules[$name];
     }
     if (class_exists($name)) {
         $this->_modules[$name] = new $name();
         return $this->_modules[$name];
     }
     if (!@$app->_conf['_modules'] or !is_array($app->_conf['_modules']) or !isset($app->_conf['_modules'][$name])) {
         return PEAR::raiseError(df_translate('scripts.Dataface.ModuleTool.loadModule.ERROR_MODULE_DOES_NOT_EXIST', "The module '{$name}' does not exist.", array('name' => $name)));
     }
     import($app->_conf['_modules'][$name]);
     if (!class_exists($name)) {
         return PEAR::raiseError(df_translate('scripts.Dataface.ModuleTool.loadModule.ERROR_CLASS_DOES_NOT_EXIST', "Attempted to load the module '{$name}' from path '{$app->_conf['_modules'][$name]}' but after loading - no such class was found.  Please check to make sure that the class is defined.  Or you can disable this module by commenting out the line that says '{$name}={$app->_conf['_modules'][$name]}' in the conf.ini file.", array('name' => $name, 'path' => $app->_conf['_modules'][$name])));
     }
     $this->_modules[$name] = new $name();
     return $this->_modules[$name];
 }
Example #7
0
 function handle(&$params)
 {
     if (!$_POST) {
         return PEAR::raiseError("This method is only available via POST");
     }
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $records = df_get_selected_records($query);
     $updated = 0;
     $errs = array();
     foreach ($records as $rec) {
         if (!$rec->checkPermission('delete')) {
             $errStr = df_translate("actions.delete_selected.permission_denied", "You do not have permission to delete '%s' because you do not have the 'delete' permission.");
             $errs[] = sprintf($errStr, $rec->getTitle());
             continue;
         }
         $res = $rec->delete(true);
         if (PEAR::isError($res)) {
             $errs[] = $res->getMessage();
         } else {
             $updated++;
         }
     }
     if ($errs) {
         $_SESSION['--msg'] = df_translate('Errors Occurred', 'Errors Occurred') . ':<br/> ' . implode('<br/> ', $errs);
     } else {
         $_SESSION['--msg'] = df_translate('No errors occurred', "No errors occurred");
     }
     $url = $app->url('-action=list');
     if (@$_POST['--redirect']) {
         $url = base64_decode($_POST['--redirect']);
     }
     $msgStr = df_translate('x records were deleted', '%d records were deleted.');
     $msgStr = sprintf($msgStr, $updated);
     $url .= '&--msg=' . urlencode($msgStr);
     $app->redirect($url);
 }
Example #8
0
 function listHtml($prefix = '')
 {
     $app =& Dataface_Application::getInstance();
     $rs =& $this->_resultSet;
     $pages = array();
     $start = $rs->start();
     $end = $rs->end();
     $limit = max($rs->limit(), 1);
     $found = $rs->found();
     // we show up to 5 pages on either side of the current position
     $pages_before = ceil(floatval($start) / floatval($limit));
     $pages_after = ceil(floatval($found - $end - 1) / floatval($limit));
     $curr_page = $pages_before + 1;
     $total_pages = $pages_before + $pages_after + 1;
     //$i = $curr_page;
     $i_start = $start;
     for ($i = $curr_page; $i > max(0, $curr_page - 5); $i--) {
         $pages[$i] = $app->url('-' . $prefix . 'limit=' . $limit . '&-' . $prefix . 'skip=' . max($i_start, 0));
         if ($this->_baseUrl) {
             $pages[$i] = $this->_baseUrl . '?' . substr($pages[$i], strpos($pages[$i], '?') + 1);
         }
         $i_start -= $limit;
     }
     //$i = $curr_page+1;
     $i_start = $start + $limit;
     for ($i = $curr_page + 1; $i <= min($total_pages, $curr_page + 5); $i++) {
         $pages[$i] = $app->url('-' . $prefix . 'limit=' . $limit . '&-' . $prefix . 'skip=' . $i_start);
         if ($this->_baseUrl) {
             $pages[$i] = $this->_baseUrl . '?' . substr($pages[$i], strpos($pages[$i], '?') + 1);
         }
         $i_start += $limit;
     }
     ksort($pages);
     $pages2 = array();
     if ($curr_page > 1) {
         $pages2[df_translate('scripts.GLOBAL.LABEL_PREV', 'Prev')] = $pages[$curr_page - 1];
     }
     foreach ($pages as $pageno => $pageval) {
         $pages2[$pageno] = $pageval;
     }
     if ($curr_page < $total_pages) {
         $pages2[df_translate('scripts.GLOBAL.LABEL_NEXT', 'Next')] = $pages[$curr_page + 1];
     }
     $out = array('<ul class="resultController">');
     $out[] = '<li class="rs-description">' . df_translate('scripts.GLOBAL.MESSAGE_FOUND', 'Found ' . $found . ' records', array('found' => $found)) . ' </li>';
     foreach ($pages2 as $pageno => $link) {
         if ($pageno == $curr_page) {
             $selected = ' selected';
         } else {
             $selected = '';
         }
         $out[] = '<li class="' . $selected . '"><a href="' . df_escape($link) . '">' . $pageno . '</a></li>';
     }
     $appurl = $app->url('');
     $appurl = preg_replace('/[&\\?]' . preg_quote('-' . $prefix . 'limit=') . '[^&]*/', '', $appurl);
     $appurl = preg_replace('/[&\\?]' . preg_quote('-' . $prefix . 'skip=') . '[^&]*/', '', $appurl);
     $urlprefix = $this->_baseUrl ? $this->_baseUrl . '?' . substr($appurl, strpos($appurl, '?') + 1) : $appurl;
     $out[] = '<li class="results-per-page"> ' . df_translate('scripts.GLOBAL.LABEL_SHOWING', 'Showing') . ' <input type="text" value="' . $limit . '" onchange="window.location = \'' . $urlprefix . '&-' . $prefix . 'limit=\'+this.value" size="3"/>' . df_translate('scripts.GLOBAL.MESSAGE_RESULTS_PER_PAGE', 'Results per page');
     $out[] = '</ul>';
     return implode("\n", $out);
 }
Example #9
0
 /**
  * Loads a module and returns a reference to it.
  * @param string $name The name of the module's class.
  *
  */
 function &loadModule($name, $path = null)
 {
     if (!isset($path)) {
         if (preg_match('/^modules_/', $name)) {
             $s = DIRECTORY_SEPARATOR;
             $path = preg_replace('/^modules_/', 'modules' . $s, $name) . $s . substr($name, strpos($name, '_') + 1) . '.php';
         }
     }
     $app =& Dataface_Application::getInstance();
     if (isset($this->_modules[$name])) {
         return $this->_modules[$name];
     }
     if (class_exists($name)) {
         $this->_modules[$name] = new $name();
         return $this->_modules[$name];
     }
     if (!isset($path) and (!@$app->_conf['_modules'] or !is_array($app->_conf['_modules']) or !isset($app->_conf['_modules'][$name]))) {
         return PEAR::raiseError(df_translate('scripts.Dataface.ModuleTool.loadModule.ERROR_MODULE_DOES_NOT_EXIST', "The module '{$name}' does not exist.", array('name' => $name)));
     }
     if (!isset($app->_conf['_modules'][$name]) and isset($path)) {
         $app->_conf['_modules'][$name] = $path;
         import($path);
         if ($this->getFsVersion($name, $path) > $this->getDbVersion($name)) {
             $this->updateModule($name, $path);
         }
     } else {
         import($app->_conf['_modules'][$name]);
         if ($this->getFsVersion($name, $app->_conf['_modules'][$name]) > $this->getDbVersion($name)) {
             $this->updateModule($name, $app->_conf['_modules'][$name]);
         }
     }
     if (!class_exists($name)) {
         return PEAR::raiseError(df_translate('scripts.Dataface.ModuleTool.loadModule.ERROR_CLASS_DOES_NOT_EXIST', "Attempted to load the module '{$name}' from path '{$app->_conf['_modules'][$name]}' but after loading - no such class was found.  Please check to make sure that the class is defined.  Or you can disable this module by commenting out the line that says '{$name}={$app->_conf['_modules'][$name]}' in the conf.ini file.", array('name' => $name, 'path' => $app->_conf['_modules'][$name])));
     }
     $this->_modules[$name] = new $name();
     return $this->_modules[$name];
 }
Example #10
0
    function getResultFilters()
    {
        ob_start();
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        echo '<div class="resultlist-filters">
		<h3>' . df_translate('scripts.Dataface_ResultList.MESSAGE_FILTER_RESULTS', 'Filter Results') . ':</h3>
		<script language="javascript"><!--
		
		function resultlist__updateFilters(col,select){
			var currentURL = "' . $app->url('') . '";
			var currentParts = currentURL.split("?");
			var currentQuery = "?"+currentParts[1];
			var value = select.options[select.selectedIndex].value;
			var regex = new RegExp(\'([?&])\'+col+\'={1,2}[^&]*\');
			if ( currentQuery.match(regex) ){
				if ( value ){
					prefix = "=";
				} else {
					prefix = "";
				}
				currentQuery = currentQuery.replace(regex, \'$1\'+col+\'=\'+prefix+encodeURIComponent(value));
			} else {
				currentQuery += \'&\'+col+\'==\'+encodeURIComponent(value);
			}
			window.location=currentParts[0]+currentQuery;
		}
		//--></script>
		<ul>';
        $qb = new Dataface_QueryBuilder($this->_table->tablename, $query);
        foreach ($this->_filterCols as $col) {
            $field =& $this->_table->getField($col);
            unset($vocab);
            if (isset($field['vocabulary'])) {
                $vocab =& $this->_table->getValuelist($field['vocabulary']);
            } else {
                $vocab = null;
            }
            echo '<li> ' . htmlspecialchars($field['widget']['label']) . ' <select onchange="resultlist__updateFilters(\'' . addslashes($col) . '\', this);"><option value="">' . df_translate('scripts.GLOBAL.LABEL_ALL', 'All') . '</option>';
            $res = df_query("select `{$col}`, count(*) as `num` " . $qb->_from() . " " . $qb->_secure($qb->_where(array($col => null))) . " group by `{$col}`", null, true);
            if (!$res and !is_array($res)) {
                trigger_error(mysql_error(df_db()), E_USER_ERROR);
            }
            if (@$query[$col] and $query[$col][0] == '=') {
                $queryColVal = substr($query[$col], 1);
            } else {
                $queryColVal = @$query[$col];
            }
            //while ( $row = mysql_fetch_assoc($res) ){
            foreach ($res as $row) {
                if (isset($vocab) and isset($vocab[$row[$col]])) {
                    $val = $vocab[$row[$col]];
                } else {
                    $val = $row[$col];
                }
                if ($queryColVal == $row[$col]) {
                    $selected = ' selected';
                } else {
                    $selected = '';
                }
                echo '<option value="' . htmlspecialchars($row[$col]) . '"' . $selected . '>' . htmlspecialchars($val) . ' (' . $row['num'] . ')</option>';
            }
            //@mysql_free_result($res);
            echo '</select></li>';
        }
        echo '</ul></div>';
        $out = ob_get_contents();
        ob_end_clean();
        return $out;
    }
Example #11
0
 /**
  * @brief Creates and HTML_QuickForm group that can be added a a QuickForm object
  * to serve as the submit buttons for edit (or new record) forms. 
  * By default this will create buttons for each tab, a back, next, and 
  * save buttons.
  *
  * CSS is used to hide the tabs by default.
  *
  * @return array(HTML_QuickForm_element) An array of submit elements.
  *
  */
 function createRecordButtons($record, $currentTab = null)
 {
     $factory =& self::factory();
     $out = array();
     $tabs = $record->tabs();
     $tabnames = array_keys($tabs);
     if (count($tabnames) > 0 and !isset($currentTab)) {
         $currentTab = $tabnames[0];
     }
     $saveButtonLabel = df_translate('tables.' . $record->table()->tablename . '.save_button_label', '');
     if (!$saveButtonLabel) {
         $saveButtonLabel = df_translate('save_button_label', 'Save');
     }
     $out[] = $factory->createElement('submit', '--session:save', $saveButtonLabel);
     if (isset($currentTab) and count($tabnames) > 1) {
         if (isset($tabs[$currentTab]['actions']['default'])) {
             $default = $tabs[$currentTab]['actions']['default'];
         } else {
             $default = '__save__';
         }
         $out[] = $factory->createElement('submit', '--session:target:__default__', $default, array('style' => 'display:none'));
         $currIndex = array_search($currentTab, $tabnames);
         $next = isset($tabnames[$currIndex + 1]) ? $tabnames[$currIndex + 1] : null;
         $prev = isset($tabnames[$currIndex - 1]) ? $tabnames[$currIndex - 1] : null;
         if (isset($tabs[$currentTab]['actions']['next'])) {
             $next = $tabs[$currentTab]['actions']['next'];
         }
         if (isset($tabs[$currentTab]['actions']['back'])) {
             $prev = $tabs[$currentTab]['actions']['back'];
         }
         $default = null;
         if (isset($tabs[$currentTab]['actions']['default'])) {
             $default = $tabs[$currentTab]['actions']['default'];
         }
         foreach ($tabs as $tab) {
             if (@$params['tab'] == $tab['name']) {
                 continue;
             }
             // we don't include a button to the current tab
             $tabname = $tab['name'];
             $atts = array();
             if (isset($tab['button']['atts'])) {
                 $atts = $tab['button']['atts'];
             }
             if (isset($params['atts']['__global__'])) {
                 $atts = array_merge($atts, $params['atts']['__global__']);
             }
             if (isset($params['atts'][$tab])) {
                 $atts = array_merge($atts, $params['atts'][$tab]);
             }
             if (!isset($atts['style'])) {
                 $atts['style'] = 'display: none';
             }
             $out[] = $factory->createElement('submit', '--session:target:' . $tabname, $tab['label'], $atts);
         }
     }
     if (isset($prev)) {
         $out[] = $factory->createElement('submit', '--session:target:__back__', df_translate('scripts.GLOBAL.LABEL_BACK', 'Back'));
     }
     if (isset($next)) {
         $out[] = $factory->createElement('submit', '--session:target:__next__', df_translate('scripts.GLOBAL.LABEL_NEXT', 'Next'));
     }
     return $out;
 }
Example #12
0
 function handle(&$params)
 {
     import('Dataface/FormTool.php');
     import('Dataface/QuickForm.php');
     $formTool =& Dataface_FormTool::getInstance();
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     $currentRecord =& $app->getRecord();
     $currentTable =& Dataface_Table::loadTable($query['-table']);
     if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) {
         $tabs = $currentTable->tabs($currentRecord);
         uasort($tabs, array($formTool, '_sortTabs'));
         list($query['--tab']) = array_keys($tabs);
     } else {
         if (count($currentTable->tabs($currentRecord)) <= 1) {
             unset($query['--tab']);
         }
     }
     $includedFields = null;
     // Null for all fields
     if (@$query['-fields']) {
         $includedFields = explode(' ', $query['-fields']);
     }
     /*
      *
      * Create the quickform for the current record.
      *
      */
     //$form = new Dataface_QuickForm($query['-table'], $app->db(),  $query);
     if ($resultSet->found() > @$query['-cursor']) {
         $form = $formTool->createRecordForm($currentRecord, false, @$query['--tab'], $query, $includedFields);
         /*
          * There is either a result to edit, or we are creating a new record.
          *
          */
         $res = $form->_build();
         if (PEAR::isError($res)) {
             error_log($res->toString() . implode("\n", $res->getBacktrace()));
             throw new Exception("An error occurred while building the edit form.  See error log for details.", E_USER_ERROR);
         }
         $formTool->decorateRecordForm($currentRecord, $form, false, @$query['--tab']);
         /*
          *
          * We need to add the current GET parameter flags (the GET vars starting with '-') so
          * that the controller knows to pass control to this method again upon form submission.
          *
          */
         foreach ($query as $key => $value) {
             if (strpos($key, '-') === 0) {
                 $form->addElement('hidden', $key);
                 $form->setDefaults(array($key => $value));
             }
         }
         /*
          * Store the current query string (the portion after the '?') in the form, so we 
          * can retrieve it after and redirect back to our original location.
          */
         $form->addElement('hidden', '-query');
         $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING']));
         /*
          * 
          * We have to deal with 3 cases.
          * 	1) The form has not been submitted.
          *	2) The form was submitted but didn't validate (ie: it had some bad input)
          * 	3) The form was submitted and was validated.
          *
          * We deal with Case 3 first...
          *
          */
         if ($formTool->validateRecordForm($currentRecord, $form, false, @$query['--tab'])) {
             /*
              *
              * The form was submitted and it validated ok.  We now process it (ie: save its contents).
              *
              */
             $app->clearMessages();
             $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']);
             if (!isset($query['--tab'])) {
                 // If we aren't using tabs we just do it the old way.
                 // (If it ain't broke don't fix it
                 $result = $form->process(array(&$form, 'save'));
             } else {
                 // If we are using tabs, we will use the formtool's
                 // session aware saving function
                 $result = $formTool->saveSession($currentRecord);
             }
             $success = true;
             $response =& Dataface_Application::getResponse();
             if (!$result) {
                 error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace());
                 throw new Exception("An error occurred while attempting to save the record.  See error log for details.", E_USER_ERROR);
             } else {
                 if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) {
                     if (Dataface_Error::isDuplicateEntry($result)) {
                         $app->addError($result);
                         $success = false;
                     } else {
                         error_log($result->toString() . implode("\n", $result->getBacktrace()));
                         throw new Exception("An error occurred while attempting to save the record.  See error log for details.", E_USER_ERROR);
                     }
                 } else {
                     if (Dataface_Error::isNotice($result)) {
                         $app->addError($result);
                         //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage();
                         $success = false;
                     }
                 }
             }
             if ($success) {
                 if (@$query['-response'] == 'json') {
                     //header('Content-type: text/html; charset="'.$app->_conf['oe'].'"');
                     $rvals = $currentRecord->strvals();
                     $rvals['__title__'] = $currentRecord->getTitle();
                     $rvals['__id__'] = $currentRecord->getId();
                     echo df_escape(json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved'))));
                     return;
                 }
                 import('Dataface/Utilities.php');
                 Dataface_Utilities::fireEvent('after_action_edit', array('record' => $form->_record));
                 /*
                  *
                  * The original query string will have the -new flag set.  We need to remove this 
                  * flag so that we don't redirect the user to create another new record.
                  *
                  */
                 $vals = $form->exportValues();
                 $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']);
                 $_SESSION['--last_modified_record_url'] = $form->_record->getURL();
                 $_SESSION['--last_modified_record_title'] = $form->_record->getTitle();
                 $msg = implode("\n", $app->getMessages());
                 //$msg =@$response['--msg'];
                 $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg);
                 if (preg_match('/[&\\?]-action=edit&/', $vals['-query']) and !$form->_record->checkPermission('edit')) {
                     $vals['-query'] = preg_replace('/([&\\?])-action=edit&/', '$1-action=view&', $vals['-query']);
                 } else {
                     if (preg_match('/[&\\?]-action=edit$/', $vals['-query']) and !$form->_record->checkPermission('edit')) {
                         $vals['-query'] = preg_replace('/([&\\?])-action=edit$/', '$1-action=view', $vals['-query']);
                     }
                 }
                 $vals['-query'] = preg_replace('/&?--msg=[^&]*/', '', $vals['-query']);
                 if (@$query['--lang']) {
                     $vals['-query'] .= '&--lang=' . $query['--lang'];
                 }
                 $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--saved=1&--msg=' . $msg;
                 /*
                  *
                  * Redirect the user to the appropriate record.
                  *
                  */
                 $app->redirect("{$link}");
             }
         }
         ob_start();
         $form->display();
         $out = ob_get_contents();
         ob_end_clean();
         if (count($form->_errors) > 0) {
             $app->clearMessages();
             $app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>" . implode('</li><li>', $form->_errors) . "</li></ul>"));
         }
         $context = array('form' => $out);
         // Now let's add the tabs to the context
         $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']);
     } else {
         // no records were found
         $context = array('form' => '');
         if (isset($_SESSION['--last_modified_record_url'])) {
             $lastModifiedURL = $_SESSION['--last_modified_record_url'];
             $lastModifiedTitle = $_SESSION['--last_modified_record_title'];
             unset($_SESSION['--last_modified_record_title']);
             unset($_SESSION['--last_modified_record_url']);
             $app->addMessage(df_translate('Return to last modified record', 'No records matched your request.  Click <a href="' . $lastModifiedURL . '">here</a> to return to <em>' . df_escape($lastModifiedTitle) . '</em>.', array('lastModifiedURL' => $lastModifiedURL, 'lastModifiedTitle' => $lastModifiedTitle)));
         } else {
             $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request'));
         }
         $query['-template'] = 'Dataface_Main_Template.html';
     }
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (@$query['-headless']) {
             $template = 'Dataface_Edit_Record_headless.html';
         } else {
             if (isset($params['action']['template'])) {
                 $template = $params['action']['template'];
             } else {
                 $template = 'Dataface_Edit_Record.html';
             }
         }
     }
     df_display($context, $template, true);
 }
Example #13
0
    public function reset_password_with_uuid($uuid)
    {
        $auth = Dataface_AuthenticationTool::getInstance();
        $app = Dataface_Application::getInstance();
        $del = $app->getDelegate();
        $this->create_reset_password_table();
        $this->clear_expired();
        $table = self::$TABLE_RESET_PASSWORD;
        $res = xf_db_query("select * from `{$table}` where request_uuid='" . addslashes($uuid) . "' limit 1", df_db());
        if (!$res) {
            throw new Exception(xf_db_error(df_db()));
        }
        $row = xf_db_fetch_assoc($res);
        if (!$row) {
            throw new Exception(df_translate('actions.forgot_password.no_such_reset_request_found', "No such reset request could be found"), self::$EX_NO_SUCH_UUID);
        }
        if (!$row['username']) {
            throw new Exception(df_translate('actions.forgot_password.attempt_to_reset_for_null_username', "Attempt to reset password for user with null username"), self::$EX_NO_USERNAME_FOR_USER);
        }
        $username = $row['username'];
        @xf_db_free_result($res);
        // now that we have the username, let's reset the password.
        //$rand = strval(rand())."".$uuid;
        $rand = md5($uuid);
        error_log("Rand is " . $rand);
        $pw = '';
        for ($i = 0; $i <= 16; $i += 2) {
            $pw .= $rand[$i];
        }
        $password = $pw;
        if (isset($del) and method_exists($del, 'generateTemporaryPassword')) {
            $pw = $del->generateTemporaryPassword();
            if ($pw) {
                $password = $pw;
            }
        }
        //error_log("Password is $password");
        $user = df_get_record($auth->usersTable, array($auth->usernameColumn => '=' . $username));
        if (!$user) {
            throw new Exception(df_translate('actions.forgot_password.no_account_for_username', "No user account found with that username"), self::$EX_USER_NOT_FOUND);
        }
        $emailColumn = $auth->getEmailColumn();
        if (!$emailColumn) {
            throw new Exception(df_translate('actions.forgot_password.no_email_column_found_short', "No email column found in the users table"), self::$EX_NO_EMAIL_COLUMN_FOUND);
        }
        $email = $user->val($emailColumn);
        if (!$email) {
            throw new Exception(df_translate('actions.forgot_password.user_without_email_long', "User has account has no email address on record.  Please contact support to reset the password"), self::$EX_NO_EMAIL_FOR_USER);
        }
        $user->setValue($auth->passwordColumn, $password);
        $res = $user->save();
        if (PEAR::isError($res)) {
            throw new Exception($res->getMessage());
        }
        // Let's delete this request from the password reset requests.
        $this->delete_request_with_uuid($uuid);
        // Now let's send the email.
        $del = $app->getDelegate();
        $info = array();
        if (isset($del) and method_exists($del, 'getPasswordChangedEmailInfo')) {
            $info = $del->getPasswordChangedEmailInfo($user, $password);
        }
        $subject = df_translate('actions.forgot_password.password_changed', "Password Changed");
        if (isset($info['subject'])) {
            $subject = $info['subject'];
        }
        $site_url = df_absolute_url(DATAFACE_SITE_HREF);
        $msg = df_translate('actions.forgot_password.new_temporary_password_email_body', <<<END
Your new temporary password is
{$password}

You can change your password as follows:

1. Log in with your temporary password at <{$site_url}?-action=login>
2. Click on the "My Profile" link in the upper right of the page
3. Click on the "Edit" tab.
4. Change your password in the edit form and click "Save" when done.
END
, array('password' => $password, 'site_url' => $site_url));
        if (isset($info['message'])) {
            $msg = $info['message'];
        }
        $parameters = null;
        if (isset($info['parameters'])) {
            $parameters = $info['parameters'];
        }
        $site_title = $app->getSiteTitle();
        $support_email = $_SERVER['SERVER_ADMIN'];
        if (isset($app->_conf['admin_email'])) {
            $support_email = $app->_conf['admin_email'];
        }
        if (isset($app->_conf['support_email'])) {
            $support_email = $app->_conf['support_email'];
        }
        $headers = 'From: ' . $site_title . ' <' . $support_email . '>' . "\r\nReply-to: " . $site_title . " <" . $support_email . ">" . "\r\nContent-type: text/plain; charset=" . $app->_conf['oe'];
        if (isset($info['headers'])) {
            $headers = $info['headers'];
        }
        if (@$app->_conf['_mail']['func']) {
            $func = $app->_conf['_mail']['func'];
        } else {
            $func = 'mail';
        }
        $res = $func($email, $subject, $msg, $headers, $parameters);
        if (!$res) {
            return PEAR::raiseError(df_translate('actions.forgot_password.failed_send_activation', "Failed to send activation email.  Please try again later."), DATAFACE_E_ERROR);
        } else {
            return true;
        }
    }
Example #14
0
 function handle(&$params)
 {
     import('Dataface/ExistingRelatedRecordForm.php');
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     //$record =& $app->getRecord();	// loads the current record
     if (!isset($query['-relationship'])) {
         return PEAR::raiseError(Dataface_LanguageTool::translate('Error: No relationship specified', 'Error.  No relationship was specified when trying to add existing related record.'), DATAFACE_E_NOTICE);
     }
     $record = null;
     $form = new Dataface_ExistingRelatedRecordForm($record, $query['-relationship']);
     $res = $form->_build();
     if (PEAR::isError($res)) {
         return Dataface_Error::permissionDenied($res->getMessage());
     }
     /*
      *
      * We need to add the current GET parameter flags (the GET vars starting with '-') so
      * that the controller knows to pass control to this method again upon form submission.
      *
      */
     foreach ($query as $key => $value) {
         if (strpos($key, '-') === 0) {
             $form->addElement('hidden', $key);
             $form->setDefaults(array($key => $value));
         }
     }
     /*
      * Store the current query string (the portion after the '?') in the form, so we 
      * can retrieve it after and redirect back to our original location.
      */
     $form->addElement('hidden', '-query');
     $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING']));
     if (!$form->_record || !is_a($form->_record, 'Dataface_Record')) {
         trigger_error(Dataface_LanguageTool::translate('Fatal Error', 'Fatal Error: Form should have loaded record but the record was null. ' . Dataface_Error::printStackTrace(), array('stack_trace' => Dataface_Error::printStackTrace(), 'msg' => 'Form should have loaded record but the record was null.')), E_USER_ERROR);
     }
     if (!Dataface_PermissionsTool::checkPermission('add existing related record', $form->_record)) {
         return Dataface_Error::permissionDenied(Dataface_LanguageTool::translate('Error: Permission denied adding existing related record', 'Permission Denied.  You do not have sufficient permissions to add an existing related record.  Required permission: "add existing related record", but you have only been granted permissions: "' . implode(',', $form->_record->getPermissions()) . '".', array('required_permission' => 'add existing related record', 'granted_permissions' => implode(',', $form->_record->getPermissions()))));
     }
     if ($form->validate()) {
         $res = $form->process(array(&$form, 'save'), true);
         $response =& Dataface_Application::getResponse();
         if (PEAR::isError($res) && !Dataface_Error::isNotice($res)) {
             return $res;
         } else {
             if (Dataface_Error::isNotice($res)) {
                 //$response['--msg'] = @$response['--msg'] . "\n".$res->getMessage();
                 $app->addError(PEAR::raiseError(df_translate('Failed to add record because of errors', 'Failed to add record to relationship because of the following errors:'), DATAFACE_E_NOTICE));
                 $app->addError($res);
                 $success = false;
             } else {
                 $success = true;
             }
         }
         if ($success) {
             import('Dataface/Utilities.php');
             Dataface_Utilities::fireEvent('after_action_existing_related_record');
             $fquery = array('-action' => 'browse');
             $msg = Dataface_LanguageTool::translate('Record successfully added to relationship', "The record has been successfully added to the " . $query['-relationship'] . " relationship.\n", array('relationship' => $query['-relationship']));
             $msg = urlencode(trim(($success ? $msg : '') . @$response['--msg']));
             $vals = $form->exportValues();
             if (isset($vals['--redirect'])) {
                 $qmark = strpos($vals['--redirect'], '?') !== false ? '&' : '?';
                 header('Location: ' . $vals['--redirect'] . $qmark . '--msg=' . $msg);
                 exit;
             }
             foreach ($vals['__keys__'] as $key => $value) {
                 $fquery[$key] = "=" . $value;
             }
             $link = Dataface_LinkTool::buildLink($fquery);
             header("Location: {$link}" . "&--msg=" . $msg);
             exit;
         }
     }
     ob_start();
     $form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('form' => $out);
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (isset($params['action']['template'])) {
             $template = $params['action']['template'];
         } else {
             $template = 'Dataface_Add_Existing_Related_Record.html';
         }
     }
     df_display($context, $template, true);
 }
Example #15
0
 function df_offset($date)
 {
     if (!$date) {
         return df_translate('scripts.global.MESSAGE_UNKNOWN', 'Unknown');
     }
     $date = strtotime($date);
     $offset = strftime("%j") + strftime("%Y") * 365 - (strftime("%j", $date) + strftime("%Y", $date) * 365);
     if ($offset > 7) {
         $offset = strftime("%W") + strftime("%Y") * 52 - (strftime("%W", $date) + strftime("%Y", $date) * 52);
         $end = $offset != 0 ? $offset > 1 ? $offset . " weeks ago" : "a week ago" : "Today";
     } else {
         $end = $offset != 0 ? $offset > 1 ? "{$offset} days ago" : "Yesterday" : "Today";
     }
     return strftime("%A, %B %d, %Y", $date) . " - " . $end;
 }
Example #16
0
 function df_offset($date)
 {
     if (!$date) {
         return df_translate('scripts.global.MESSAGE_UNKNOWN', 'Unknown');
     }
     $xWeeksAgoStr = df_translate('x weeks ago', "%d weeks ago");
     $xDaysAgoStr = df_translate('x days ago', "%d days ago");
     $todayStr = df_translate('Today', "Today");
     $yesterdayStr = df_translate('Yesterday', "Yesterday");
     $aWeekAgoStr = df_translate("a week ago", "a week ago");
     $date = strtotime($date);
     $offset = strftime("%j") + strftime("%Y") * 365 - (strftime("%j", $date) + strftime("%Y", $date) * 365);
     if ($offset > 7) {
         $offset = strftime("%W") + strftime("%Y") * 52 - (strftime("%W", $date) + strftime("%Y", $date) * 52);
         $end = $offset != 0 ? $offset > 1 ? sprintf($xWeeksAgoStr, $offset) : $aWeekAgoStr : $todayStr;
     } else {
         $end = $offset != 0 ? $offset > 1 ? sprintf($xDaysAgoStr, $offset) : $yesterdayStr : $todayStr;
     }
     return strftime("%A, %B %d, %Y", $date) . " - " . $end;
 }
Example #17
0
 function save($values)
 {
     // First let's find out if we should SAVE the data or if we should just be
     // storing it in the session or if we are saving the data to the database
     if (!$this->_new) {
         // Make sure that the correct form is being submitted.
         if (!isset($values['__keys__'])) {
             throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR);
         }
         if (array_keys($values['__keys__']) != array_keys($this->_table->keys())) {
             throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR);
         }
     }
     if ($this->_new) {
         $this->_record->clearValues();
     }
     $res = $this->push();
     if (!$this->_new) {
         if ($this->_record->snapshotExists()) {
             $tempRecord = new Dataface_Record($this->_record->_table->tablename, $this->_record->getSnapshot());
         } else {
             $tempRecord =& $this->_record;
         }
         if ($values['__keys__'] != $tempRecord->strvals(array_keys($this->_record->_table->keys()))) {
             throw new Exception(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving record in QuickForm::save().\n<br>"), E_USER_ERROR);
         }
     }
     if (PEAR::isError($res)) {
         $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_PUSHING_DATA', "Error pushing data from form onto table in QuickForm::save() ", array('line' => 0, 'file' => "_")));
         return $res;
     }
     // Let's take an inventory of which fields were changed.. because
     // we are going to make their values available in the htmlValues()
     // method which is used by the ajax form to gather updates.
     foreach ($this->_fields as $changedfield) {
         if ($this->_record->valueChanged($changedfield['name'])) {
             $this->_changed_fields[] = $changedfield['name'];
         }
     }
     $io = new Dataface_IO($this->tablename, $this->db);
     $io->lang = $this->_lang;
     if ($this->_new) {
         $keys = null;
     } else {
         $keys = $values['__keys__'];
     }
     $res = $io->write($this->_record, $keys, null, true, $this->_new);
     if (PEAR::isError($res)) {
         if (Dataface_Error::isDuplicateEntry($res)) {
             /*
              * If this is a duplicate entry (or just a notice - not fatal), we will propogate the exception up to let the application
              * decide what to do with it.
              */
             return $res;
         }
         if (Dataface_Error::isNotice($res)) {
             return $res;
         }
         $res->addUserInfo(df_translate('scripts.Dataface.QuickForm.save.ERROR_SAVING_RECORD', "Error saving form in QuickForm::save()", array('line' => 0, 'file' => "_")));
         throw new Exception($res->toString(), E_USER_ERROR);
     }
     if (isset($io->insertIds[$this->tablename]) and $this->_table->getAutoIncrementField()) {
         $this->_record->setValue($this->_table->getAutoIncrementField(), $io->insertIds[$this->tablename]);
         $this->_record->setSnapshot();
     }
     return true;
 }
Example #18
0
 function Dataface_RecordView(&$record)
 {
     $this->record =& $record;
     $tablename = $this->record->_table->tablename;
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $collapseAll = false;
     $expandAll = false;
     $collapsedSections = array();
     $expandedSections = array();
     if (@$query['--collapse-all']) {
         $collapseAll = true;
     }
     if (@$query['--expand-all']) {
         $expandAll = true;
     }
     if (@$query['--collapsed-sections']) {
         $collapsedSections = array_flip(explode(',', $query['--collapsed-sections']));
     }
     if (@$query['--expanded-sections']) {
         $expandedSections = array_flip(explode(',', $query['--expanded-sections']));
     }
     $fields = $this->record->_table->fields(false, true);
     // Now get defined sidebars in the delegate class.
     $this->sidebars = array();
     $this->sections = array();
     $this->description = $record->getDescription();
     if (intval($record->getLastModified()) > 0) {
         $this->status = sprintf(df_translate('Last updated date', 'Last updated %s'), df_offset(date('Y-m-d H:i:s', intval($record->getLastModified()))));
     } else {
         $this->status = '';
     }
     import('Dataface/PreferencesTool.php');
     $pt =& Dataface_PreferencesTool::getInstance();
     $prefs =& $pt->getPreferences($record->getId());
     $delegate =& $this->record->_table->getDelegate();
     if (isset($delegate)) {
         $delegate_methods = get_class_methods(get_class($delegate));
         $delegate_sidebars = preg_grep('/^sidebar__/', $delegate_methods);
         $delegate_fields = preg_grep('/^field__/', $delegate_methods);
         $delegate_sections = preg_grep('/^section__/', $delegate_methods);
         foreach ($delegate_fields as $dfield) {
             $dfieldname = substr($dfield, 7);
             $fields[$dfieldname] = $this->record->_table->_newSchema('varchar(32)', $dfieldname);
             $fields[$dfieldname]['visibility']['browse'] = 'hidden';
             if (isset($this->record->_table->_atts[$dfieldname]) and is_array($this->record->_table->_atts[$dfieldname])) {
                 $this->record->_table->_parseINISection($this->record->_table->_atts[$dfieldname], $fields[$dfieldname]);
             }
         }
         foreach ($delegate_sidebars as $sb) {
             $this->sidebars[] = $delegate->{$sb}($this->record);
         }
         foreach ($delegate_sections as $sec) {
             $secobj = $delegate->{$sec}($this->record);
             if (!isset($secobj['name'])) {
                 $secobj['name'] = substr($sec, 9);
             }
             if (isset($prefs['tables.' . $tablename . '.sections.' . $secobj['name'] . '.order'])) {
                 $secobj['order'] = intval($prefs['tables.' . $tablename . '.sections.' . $secobj['name'] . '.order']);
             }
             if (isset($prefs['tables.' . $tablename . '.sections.' . $secobj['name'] . '.display'])) {
                 $secobj['display'] = $prefs['tables.' . $tablename . '.sections.' . $secobj['name'] . '.display'];
             } else {
                 $secobj['display'] = 'expanded';
             }
             if ($expandAll) {
                 $secobj['display'] = 'expanded';
             }
             if ($collapseAll) {
                 $secobj['display'] = 'collapsed';
             }
             if (isset($collapsedSections[$secobj['name']])) {
                 $secobj['display'] = 'collapsed';
             }
             if (isset($expandedSections[$secobj['name']])) {
                 $secobj['display'] = 'expanded';
             }
             $this->sections[] =& $secobj;
             unset($secobj);
         }
     }
     // build the field groups
     $this->fieldgroups = array();
     $this->logos = array();
     foreach ($fields as $field) {
         if (!$record->checkPermission('view', array('field' => $field['name']))) {
             continue;
         }
         if ($record->_table->isMetaField($field['name'])) {
             continue;
         }
         if (!@$app->prefs['hide_record_view_logo']) {
             if ($record->isImage($field['name']) and @$field['logo'] !== '0' or @$field['logo']) {
                 $this->showLogo = true;
                 if (!isset($field['width'])) {
                     if (isset($this->record->_table->_fields[$field['name']])) {
                         $this->record->_table->_fields[$field['name']]['width'] = 225;
                     } else {
                         $this->record->_table->_atts[$field['name']]['width'] = 225;
                     }
                 }
                 $this->logos[] = $field;
                 continue;
             } else {
                 if (@$field['image']) {
                     $this->logos[] = $field;
                     $this->showLogo = true;
                 }
             }
         }
         if ($field['visibility']['browse'] == 'hidden') {
             continue;
         }
         if (isset($field['viewgroup'])) {
             $group = $field['viewgroup'];
         } else {
             if (isset($field['group'])) {
                 $group = $field['group'];
             } else {
                 $group = '__main__';
             }
         }
         if (!isset($this->fieldgroups[$group])) {
             $this->fieldgroups[$group][$field['name']] = $field;
             $fldgrp =& $this->record->_table->getFieldGroup($group);
             $class = 'main';
             $display = 'expanded';
             if (PEAR::isError($fldgrp)) {
                 $label = ucwords(str_replace('_', ' ', $group));
                 if ($group == '__main__') {
                     $label = df_translate('Dataface_RecordView_Details_Label', "Details");
                     if (@$app->prefs['RecordView.showLastModifiedOnDetails']) {
                         $label .= ' <span style="color: #666; font-weight: normal; text-style:italic"> - Last modified ' . df_offset(date('Y-m-d', $this->record->getLastModified())) . '</span>';
                     }
                 }
                 $order = 0;
                 $class = 'main';
             } else {
                 if (isset($fldgrp['condition']) and !$app->testCondition($fldgrp['condition'], array('record' => &$this->record))) {
                     continue;
                 }
                 if (isset($fldgrp['permission']) and !$record->checkPermission($fldgrp['permission'])) {
                     continue;
                 }
                 $label = ucwords(str_replace('_', ' ', $fldgrp['label']));
                 if (isset($fldgrp['section']['order'])) {
                     $order = $fldgrp['section']['order'];
                 } else {
                     $order = 0;
                 }
                 if (isset($fldgrp['section']['class'])) {
                     $class = $fldgrp['section']['class'];
                 }
                 if (isset($fldgrp['display'])) {
                     $display = $fldgrp['display'];
                 }
             }
             $sec = array('name' => $group . '__fieldgroup', 'label' => $label, 'url' => null, 'content' => null, 'fields' => &$this->fieldgroups[$group], 'order' => $order, 'class' => $class, 'display' => $display);
             if (isset($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.order'])) {
                 $sec['order'] = intval($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.order']);
             }
             if (isset($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.display'])) {
                 $sec['display'] = $prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.display'];
             }
             if ($expandAll) {
                 $sec['display'] = 'expanded';
             }
             if ($collapseAll) {
                 $sec['display'] = 'collapsed';
             }
             if (isset($collapsedSections[$sec['name']])) {
                 $sec['display'] = 'collapsed';
             }
             if (isset($expandedSections[$sec['name']])) {
                 $sec['display'] = 'expanded';
             }
             $this->sections[] =& $sec;
             unset($sec);
             unset($fldgrp);
         } else {
             $this->fieldgroups[$group][$field['name']] = $field;
         }
     }
     if (count($this->logos) > 1) {
         $theLogo = $this->logos[0];
         if (!@$theLogo['logo']) {
             foreach ($this->logos as $logofield) {
                 if (@$logoField['logo']) {
                     $theLogo = $logoField;
                     break;
                 }
             }
         }
         $this->logos = array($theLogo);
     }
     if (!@$app->prefs['hide_related_sections']) {
         // Create the relationship sections
         foreach ($this->record->_table->relationships() as $relname => $relationship) {
             $schema =& $relationship->_schema;
             if (isset($schema['section']['visible']) and !intval($schema['section']['visible'])) {
                 continue;
             }
             if (isset($schema['section']['condition']) and !$app->testCondition($schema['section']['condition'], array('record' => &$this->record, 'relationship' => &$relationship))) {
                 continue;
             }
             if (isset($schema['action']['condition']) and !$app->testCondition($schema['action']['condition'], array('record' => &$this->record, 'relationship' => &$relationship))) {
                 continue;
             }
             if (isset($schema['action']['permission']) and !$record->checkPermission($schema['action']['permission'])) {
                 continue;
             }
             if (isset($schema['section']['permission']) and !$record->checkPermission($schema['section']['permission'])) {
                 continue;
             }
             if (isset($schema['section']['label'])) {
                 $label = $schema['section']['label'];
             } else {
                 if (isset($schema['action']['label'])) {
                     $label = $schema['action']['label'];
                 } else {
                     $label = $relname;
                 }
             }
             if (isset($schema['section']['order'])) {
                 $order = $schema['section']['order'];
             } else {
                 if (isset($schema['action']['order'])) {
                     $order = $schema['action']['order'];
                 } else {
                     $order = 0;
                 }
             }
             if (isset($schema['section']['limit'])) {
                 $limit = $schema['section']['limit'];
             } else {
                 $limit = 5;
             }
             if (isset($schema['section']['sort'])) {
                 $sort = $schema['section']['sort'];
             } else {
                 $sort = 0;
             }
             if (isset($schema['section']['filter'])) {
                 $filter = $schema['section']['filter'];
             } else {
                 $filter = 0;
             }
             $rrecords = $this->record->getRelatedRecordObjects($relname, 0, $limit, $filter, $sort);
             if (count($rrecords) == 0) {
                 continue;
             }
             $glanceList = new Dataface_GlanceList($rrecords);
             if (isset($schema['section']['class'])) {
                 $class = $schema['section']['class'];
             } else {
                 $class = 'left';
             }
             $sec = array('name' => $relname . '__relationship', 'label' => $label, 'url' => $this->record->getURL('-action=related_records_list&-relationship=' . $relname), 'content' => $glanceList->toHtml(), 'order' => $order, 'class' => $class, 'display' => 'expanded');
             if (isset($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.order'])) {
                 $sec['order'] = intval($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.order']);
             }
             if (isset($prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.display'])) {
                 $sec['display'] = $prefs['tables.' . $tablename . '.sections.' . $sec['name'] . '.display'];
             }
             if ($expandAll) {
                 $sec['display'] = 'expanded';
             }
             if ($collapseAll) {
                 $sec['display'] = 'collapsed';
             }
             if (isset($collapsedSections[$sec['name']])) {
                 $secj['display'] = 'collapsed';
             }
             if (isset($expandedSections[$sec['name']])) {
                 $sec['display'] = 'expanded';
             }
             $this->sections[] =& $sec;
             unset($sec);
             unset($schema);
             unset($relationship);
         }
     }
     usort($this->sections, array(&$this, 'section_cmp'));
 }
Example #19
0
 function &pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $element->getName();
     $val = $element->getValue();
     if ($field['repeat']) {
         //print_r(array_keys($val));
         // eg value array('value1'=>1, 'value2'=>1, ..., 'valueN'=>1)
         if (is_array($val)) {
             $out = array_keys($val);
         } else {
             $out = array();
         }
         //$res =& $s->setValue($fieldname, array_keys($val));
     } else {
         if (preg_match('/int/', @$field['Type'])) {
             $out = intval($val);
         } else {
             $out = $val;
         }
         //$res =& $s->setValue($fieldname, $val);
     }
     if (PEAR::isError($val)) {
         $val->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_PUSHING_VALUE', "Error pushing value for field '{$field['name']}' in QuickForm::pushWidget() on line " . __LINE__ . " of file " . __FILE__, array('name' => $field['name'], 'file' => __FILE__, 'line' => __LINE__)));
         return $val;
     }
     return $out;
 }
Example #20
0
 /**
  * This method sits above "display" on the output stack for a field.
  * I.e. it wraps "display()" and adds some extra filtering to make the
  * output directly appropriate to be displayed as HTML.  In text fields
  * this will convert newlines to breaks, and in blob fields, this will output
  * either the full a-href tag or img tag depending on the type of content that
  * is stored.
  * 
  * @param $fieldname The name of the field to output
  * @param $params Associative array of html parameters that can optionally
  * be supplied.
  * Returns HTML string.
  */
 function htmlValue($fieldname, $index = 0, $where = 0, $sort = 0, $params = array())
 {
     $recid = $this->getId();
     $uri = $recid . '#' . $fieldname;
     $domid = $uri . '-' . rand();
     $delegate =& $this->_table->getDelegate();
     if (isset($delegate) && method_exists($delegate, $fieldname . '__htmlValue')) {
         $methodname = $fieldname . '__htmlValue';
         $res = $delegate->{$methodname}($this);
         //$res = call_user_func(array(&$delegate, $fieldname.'__htmlValue'), $this);
         if (is_string($res) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
             $res = '<span id="' . $domid . '" df:id="' . $uri . '" class="df__editable">' . $res . '</span>';
         }
         return $res;
     }
     $parent =& $this->getParentRecord();
     if (isset($parent) and $parent->_table->hasField($fieldname)) {
         return $parent->htmlValue($fieldname, $index, $where, $sort, $params);
     }
     $val = $this->display($fieldname, $index, $where, $sort);
     if ($this->secureDisplay and !Dataface_PermissionsTool::view($this, array('field' => $fieldname))) {
         $del =& $this->_table->getDelegate();
         if ($del and method_exists($del, 'no_access_link')) {
             $link = $del->no_access_link($this, array('field' => $fieldname));
             return '<a href="' . htmlspecialchars($link) . '">' . $val . '</a>';
         }
     }
     $field = $this->_table->getField($fieldname);
     //if ( $field['widget']['type'] != 'htmlarea' ) $val = htmlentities($val,ENT_COMPAT, 'UTF-8');
     if ($this->_table->isText($fieldname) and $field['widget']['type'] != 'htmlarea') {
         $val = nl2br($val);
     }
     if ($this->_table->isBlob($fieldname) or $this->_table->isContainer($fieldname)) {
         if ($this->getLength($fieldname, $index, $where, $sort) > 0) {
             if ($this->isImage($fieldname, $index, $where, $sort)) {
                 $val = '<img src="' . $val . '"';
                 if (!isset($params['width']) and isset($field['width'])) {
                     $params['width'] = $field['width'];
                 }
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . $pkey . '="' . $pval . '"';
                 }
                 $val .= '/>';
             } else {
                 $file_icon = df_translate($this->getMimetype($fieldname, $index, $where, $sort) . ' file icon', df_absolute_url(DATAFACE_URL) . '/images/document_icon.gif');
                 $val = '<img src="' . $file_icon . '"/><a href="' . $val . '" target="_blank"';
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . $pkey . '="' . $pval . '"';
                 }
                 $val .= '>View Field Content In New Window (' . $this->getMimetype($fieldname, $index, $where, $sort) . ')</a>';
             }
         } else {
             $val = "(Empty)";
         }
     }
     if (is_string($val) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
         $val = '<span id="' . $domid . '" df:id="' . $uri . '" class="df__editable">' . $val . '</span>';
     }
     return $val;
 }
Example #21
0
 function &loadCurrent($columns = null, $loadText = true, $loadBlobs = false, $loadPasswords = false)
 {
     $app =& Dataface_Application::getInstance();
     $false = false;
     // boolean placeholders for values needing to be returned by reference
     $true = true;
     if ($this->_currentRecord === null) {
         //require_once 'Dataface/IO.php';
         //$io = new Dataface_IO($this->_table->tablename);
         //$query = array_merge( $this->_query, array('-skip'=>$this->_data['cursor'], '-limit'=>1) );
         $this->_currentRecord = new Dataface_Record($this->_table->tablename, array());
         //$io->read($query, $this->_currentRecord);
     }
     //return $this->_currentRecord;
     $unloaded = array();
     $fields =& $this->_table->fields(false, true);
     if ($columns === null) {
         $names = array_keys($fields);
     } else {
         $names = $columns;
     }
     foreach ($names as $name) {
         if (!$this->_currentRecord->isLoaded($name)) {
             if (!$loadText and $this->_table->isText($name)) {
                 continue;
             }
             if (!$loadBlobs and $this->_table->isBlob($name)) {
                 continue;
             }
             if (!$loadPasswords and $this->_table->isPassword($name)) {
                 continue;
             }
             $unloaded[] = $name;
         }
     }
     if (sizeof($unloaded) > 0) {
         $query = array_merge($this->_query, array('-skip' => $this->_data['cursor'], '-limit' => 1));
         $builder = new Dataface_QueryBuilder($this->_tablename, $query);
         $builder->selectMetaData = true;
         $builder->_omitBlobs = false;
         $sql = $builder->select($unloaded);
         //echo $sql;
         if (PEAR::isError($sql)) {
             throw new Exception($sql->toString(), E_USER_ERROR);
         }
         //echo $sql;
         $res = $this->dbObj->query($sql, $this->_db, null, true);
         if (!$res and !is_array($res)) {
             $app->refreshSchemas($this->_table->tablename);
             $res = $this->dbObj->query($sql, $this->_db, null, true);
             if (!$res and !is_array($res)) {
                 error_log(df_translate('scripts.Dataface.QueryTool.loadCurrent.ERROR_COULD_NOT_LOAD_CURRENT_RECORD', "Error: Could not load current record: ") . xf_db_error($this->_db) . "\n{$sql}");
                 throw new Exception("Failed to load current record due to an SQL error");
             }
         }
         if (count($res) <= 0) {
             return $false;
         }
         $row = $res[0];
         //xf_db_fetch_assoc($res);
         //@xf_db_free_result($row);
         if (!isset($this->_currentRecord)) {
             $this->_currentRecord = new Dataface_Record($this->_table->tablename, $row);
         } else {
             $this->_currentRecord->setValues($row);
         }
         //$this->_table->setValues($row);
         //$this->_table->setSnapshot();
         //$this->_table->deserialize();
     }
     return $this->_currentRecord;
 }
Example #22
0
 function save($values)
 {
     // Which ones were checked
     $checked = array_keys($values['--related-checkboxes']);
     // Which ones are currently part of the relationship
     $default = array_keys($this->getCheckedRecordsDefaults());
     // Which ones need to be added?
     $toAdd = array_diff($checked, $default);
     // Which ones need to be removed?
     $toRemove = array_diff($default, $checked);
     // Now we go through and remove the ones that need to be removed.
     $io = new Dataface_IO($this->record->_table->tablename);
     $messages = array();
     $successfulRemovals = 0;
     foreach ($toRemove as $id) {
         $res = $io->removeRelatedRecord($this->id2record($id));
         if (PEAR::isError($res)) {
             $messages[] = $res->getMessage();
         } else {
             $sucessfulRemovals++;
         }
     }
     // Now we go through and add the ones that need to be added.
     foreach ($toAdd as $id) {
         $res = $io->addExistingRelatedRecord($this->id2record($id));
         if (PEAR::isError($res)) {
             $messages[] = $res->getMessage();
         } else {
             $successfulAdditions++;
         }
     }
     array_unshift($messages, df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_ADDED', $successfulAdditions . ' records were successfully added to the relationship.', array('num_added' => $successfulAdditions)), df_translate('scripts.Dataface_RelationshipCheckboxForm.MESSAGE_NUM_RECORDS_REMOVED', $successfulRemovals . ' records were successfully removed from the relationship.', array('num_removed' => $successfulRemovals)));
     $_SESSION['msg'] = '<ul><li>' . implode('</li><li>', $messages) . '</li></ul>';
     header('Location: ' . $values['--query']);
     exit;
 }
Example #23
0
 /**
  * @brief Returns the label of this relationship as a singular term.  This uses the 
  * action:singular_label directive from the relationships.ini file if available.  Otherwise
  * it will attempt to singularize the label as recieved from getLabel().
  *
  * @return string
  *
  * @see df_singularize()
  */
 function getSingularLabel()
 {
     $action = $this->_sourceTable->getRelationshipsAsActions(array(), $this->_name);
     if (!isset($action['singular_label'])) {
         $label = $this->getLabel();
         $action['singular_label'] = df_singularize($label);
         $action['singular_label'] = df_translate('tables.' . $this->_sourceTable->tablename . '.relationships.' . $this->_name . '.singular_label', $action['singular_label']);
     }
     return $action['singular_label'];
 }
Example #24
0
 function handle(&$params)
 {
     $app = Dataface_Application::getInstance();
     if (!isset($_GET['code'])) {
         // We need this parameter or we can do nothing.
         return PEAR::raiseError(df_translate('actions.activate.MESSAGE_MISSING_CODE_PARAMETER', 'The code parameter is missing from your request.  Validation cannot take place.  Please check your url and try again.'), DATAFACE_E_ERROR);
     }
     // Step 0:  Find out what the redirect URL will be
     // We accept --redirect markers to specify which page to redirect
     // to after we're done.  This will usually be the page that the
     // user was on before they went to the login page.
     if (isset($_SESSION['--redirect'])) {
         $url = $_SESSION['--redirect'];
     } else {
         if (isset($_SESSION['-redirect'])) {
             $url = $_SESSION['-redirect'];
         } else {
             if (isset($_REQUEST['--redirect'])) {
                 $url = $_REQUEST['--redirect'];
             } else {
                 if (isset($_REQUEST['-redirect'])) {
                     $url = $_REQUEST['-redirect'];
                 } else {
                     $url = $app->url('-action=' . $app->_conf['default_action']);
                 }
             }
         }
     }
     if (strpos($url, '?') === false) {
         $url .= '?';
     }
     // Step 1: Delete all registrations older than time limit
     $time_limit = 24 * 60 * 60;
     // 1 day
     if (isset($params['time_limit'])) {
         $time_limit = intval($params['time_limit']);
     }
     $res = xf_db_query("delete from dataface__registrations \n\t\t\t\twhere registration_date < '" . addslashes(date('Y-m-d H:i:s', time() - $time_limit)) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to delete registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     // Step 2: Load the specified registration information
     $res = xf_db_query("select registration_data from dataface__registrations\n\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to load registration information due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     if (xf_db_num_rows($res) == 0) {
         // We didn't find any records matching the prescribed code, so
         // we redirect the user to their desired page and inform them
         // that the registration didn't work.
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_NOT_FOUND', 'No registration information could be found to match this code.  Please try registering again.');
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
     // Step 3: Check to make sure that there are no other users with the
     // same name.
     list($raw_data) = xf_db_fetch_row($res);
     $values = unserialize($raw_data);
     $appdel = $app->getDelegate();
     if (isset($appdel) and method_exists($appdel, 'validateRegistrationForm')) {
         $res = $appdel->validateRegistrationForm($values);
         if (PEAR::isError($res)) {
             $msg = $res->getMessage();
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     } else {
         $res = xf_db_query("select count(*) from \n\t\t\t\t`" . str_replace('`', '', $app->_conf['_auth']['users_table']) . "` \n\t\t\t\twhere `" . str_replace('`', '', $app->_conf['_auth']['username_column']) . "` = '" . addslashes($values[$app->_conf['_auth']['username_column']]) . "'\n\t\t\t\t", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to find user records due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         list($num) = xf_db_fetch_row($res);
         if ($num > 0) {
             $msg = df_translate('actions.activate.MESSAGE_DUPLICATE_USER', 'Registration failed because a user already exists by that name.  Try registering again with a different name.');
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     }
     // Step 4: Save the registration data and log the user in.
     $record = new Dataface_Record($app->_conf['_auth']['users_table'], array());
     $record->setValues($values);
     $res = $record->save();
     if (PEAR::isError($res)) {
         $app->redirect($url . '&--msg=' . urlencode($res->getMessage()));
     } else {
         $res = xf_db_query("delete from dataface__registrations\n\t\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to clean up old registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_COMPLETE', 'Registration complete.  You are now logged in.');
         $_SESSION['UserName'] = $record->strval($app->_conf['_auth']['username_column']);
         import('Dataface/Utilities.php');
         Dataface_Utilities::fireEvent('after_action_activate', array('record' => $record));
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
 }
Example #25
0
 function checkoutBlob($blobID)
 {
     if (!isset($this->blobs[$blobID])) {
         return PEAR::raiseError(df_translate('scripts.Dataface.DB.checkoutBlob.BLOB_DOESNT_EXIST', "Blob with ID {$blobID} doesn't exist. ", array('blobID' => $blobID)), DATAFACE_E_ERROR);
     }
     $blob = $this->blobs[$blobID];
     unset($this->blobs[$blobID]);
     return $blob;
 }
Example #26
0
 /**
  * Obtains a record from the history table given the value in the history__id column.
  * @param string $tablename The name of the base table.
  * @param integer $id The id (history__id column value).
  * @returns Dataface_Record from the history table.
  */
 function getRecordById($tablename, $id)
 {
     $htablename = $tablename . '__history';
     if (!Dataface_Table::tableExists($htablename)) {
         return PEAR::raiseError(df_translate('scripts.Dataface.HistoryTool.getDiffs.ERROR_HISTORY_TABLE_DOES_NOT_EXIST', "History table for '{$tablename}' does not exist, so we cannot obtain changes for records of that table.", array('tablename' => $tablename)), DATAFACE_E_ERROR);
     }
     $rec = df_get_record($htablename, array('history__id' => $id));
     return $rec;
 }
Example #27
0
 /**
  * Gets the permissions of an object.
  * @param $obj A Dataface_Table, Dataface_Record, or Dataface_Relationship record we wish to check.
  * @param #2 Optional field name whose permission we wish to check.
  */
 function getPermissions(&$obj, $params = array())
 {
     $me =& $this;
     if (isset($me->context)) {
         return $me->context->getPermissions($obj, $params);
     }
     if (is_a($obj, 'Dataface_Table') or is_a($obj, 'Dataface_Record') or is_a($obj, 'Dataface_RelatedRecord') or is_a($obj, 'Dataface_Relationship')) {
         //echo "Getting permissions: "; print_r($params);
         $perms = $obj->getPermissions($params);
         $me->filterPermissions($obj, $perms, $params);
         return $perms;
     }
     throw new Exception(df_translate('scripts.Dataface.PermissionsTool.getPermissions.ERROR_PARAMETER_1', 'In Dataface_PermissionsTool, expected first argument to be Dataface_Table, Dataface_Record, or Dataface_Relationship, but received ' . get_class($obj) . "\n<br>", array('class' => get_class($obj))), E_USER_ERROR);
 }
 /**
  * Deletes the appropriate records from the join table and the domain table (if requested).
  */
 function delete($values)
 {
     /*
      * Next we construct an IO object to write to the domain table.
      */
     $domainTable =& $this->getDomainTable();
     $domainIO = new Dataface_IO($domainTable->tablename);
     $records =& $this->getSelectedRecords();
     $messages = array();
     $confirmations = array();
     $warnings = array();
     $table =& $this->_record->_table;
     // This is the table of the parent record.
     $io = new Dataface_IO($table->tablename);
     $removePermission = $this->_record->checkPermission('remove related record', array('relationship' => $this->_relationshipName));
     //if ($removePermission ){
     //	$mask = array('delete'=>1);
     //} else {
     //	$mask = array();
     //}
     $deleteRequired = $this->deleteRequired();
     // Do we have to delete the domain record
     // to make the removal effective
     foreach ($records as $record) {
         // If deletion is required, we will do ou
         $res = $io->removeRelatedRecord($record, @$values['delete'], true);
         if (PEAR::isError($res)) {
             $warnings[] = $res->getMessage();
         } else {
             $confirmations[] = $confirmations[] = df_translate('Successfully deleted record', "Successfully deleted entry for record '" . $record->getTitle() . "' in table '" . $table->tablename . "'", array('title' => $record->getTitle(), 'table' => $table->tablename));
         }
     }
     return array('confirmations' => $confirmations, "warnings" => $warnings);
 }
Example #29
0
 /**
  * Import filters facilitate the importing of data into the table.
  * @return Array of Dataface_ImportFilter objects
  */
 function &getImportFilters()
 {
     import('Dataface/ImportFilter.php');
     if ($this->_importFilters === null) {
         $this->_importFilters = array();
         /*
          * Filters have not been loaded yet.. let's load them.
          *
          * Any method in the delegate file with a name of the form __import__<string>
          * is considered to be an import filter.
          *
          */
         $delegate =& $this->getDelegate();
         if ($delegate !== null) {
             $methods = get_class_methods(get_class($delegate));
             foreach ($methods as $method) {
                 $matches = array();
                 if (preg_match('/^__import__(.*)$/', $method, $matches)) {
                     $filter = new Dataface_ImportFilter($this->tablename, $matches[1], df_translate('import_filters:' . $matches[1] . ':label', ucwords(str_replace('_', ' ', $matches[1]))));
                     $this->_importFilters[$matches[1]] =& $filter;
                     unset($filter);
                 }
             }
         }
         $parent =& $this->getParent();
         if (isset($parent)) {
             $this->_importFilters = array_merge($parent->getImportFilters(), $this->_importFilters);
         }
     }
     return $this->_importFilters;
 }
Example #30
0
    function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
    {
        $table =& $record->_table;
        $widget =& $field['widget'];
        $factory = Dataface_FormTool::factory();
        $attributes = array('class' => $widget['class'], 'id' => $field['name']);
        if ($field['repeat']) {
            $attributes['multiple'] = true;
            $attributes['size'] = 5;
        }
        $options = $record->_table->getValuelist($field['vocabulary']);
        //Dataface_FormTool::getVocabulary($record, $field);
        if (!isset($options)) {
            $options = array();
        }
        $emptyOpt = array('' => df_translate('scripts.GLOBAL.FORMS.OPTION_PLEASE_SELECT', "Please Select..."));
        $opts = $emptyOpt;
        if ($record and $record->val($field['name'])) {
            if (!@$field['repeat'] and !isset($options[$record->strval($field['name'])])) {
                $opts[$record->strval($field['name'])] = $record->strval($field['name']);
            } else {
                if (@$field['repeat']) {
                    $vals = $record->val($field['name']);
                    if (is_array($vals)) {
                        foreach ($vals as $thisval) {
                            if (!isset($options[$thisval])) {
                                $opts[$thisval] = $thisval;
                            }
                        }
                    }
                }
            }
        }
        foreach ($options as $kopt => $opt) {
            $opts[$kopt] = $opt;
        }
        $el = $factory->addElement('select', $formFieldName, $widget['label'], $opts, $attributes);
        // Now to make it editable
        if (@$field['vocabulary']) {
            try {
                $rel =& Dataface_ValuelistTool::getInstance()->asRelationship($table, $field['vocabulary']);
                if ($rel and !PEAR::isError($rel)) {
                    if (!is_a($rel, 'Dataface_Relationship')) {
                        throw new Exception("The relationship object for the vocabulary " . $field['vocabulary'] . " could not be loaded.");
                    }
                    if (!$rel->getDomainTable()) {
                        throw new Exception("The relationship object for the vocabulary " . $field['vocabulary'] . " could not be loaded or the domain table could not be found");
                    }
                    $dtable = Dataface_Table::loadTable($rel->getDomainTable());
                    if ($dtable and !PEAR::isError($dtable)) {
                        $perms = $dtable->getPermissions();
                        if (@$perms['new']) {
                            $fields =& $rel->fields();
                            if (count($fields) > 1) {
                                $valfield = $fields[1];
                                $keyfield = $fields[0];
                            } else {
                                $valfield = $fields[0];
                                $keyfield = $fields[0];
                            }
                            if (strpos($valfield, '.') !== false) {
                                list($tmp, $valfield) = explode('.', $valfield);
                            }
                            if (strpos($keyfield, '.') !== false) {
                                list($tmp, $keyfield) = explode('.', $keyfield);
                            }
                            $jt = Dataface_JavascriptTool::getInstance();
                            $jt->import('RecordDialog/RecordDialog.js');
                            //$suffix =  '<script type="text/javascript" src="'.DATAFACE_URL.'/js/jquery-ui-1.7.2.custom.min.js"></script>';
                            //$suffix .= '<script type="text/javascript" src="'.DATAFACE_URL.'/js/RecordDialog/RecordDialog.js"></script>';
                            $suffix = '<a href="#" onclick="return false" id="' . df_escape($field['name']) . '-other">Other..</a>';
                            $suffix .= '<script>
							jQuery(document).ready(function($){
								$("#' . $field['name'] . '-other").each(function(){
									var tablename = "' . addslashes($dtable->tablename) . '";
									var valfld = ' . json_encode($valfield) . ';
									var keyfld = ' . json_encode($keyfield) . ';
									var fieldname = ' . json_encode($field['name']) . ';
									var btn = this;
									$(this).RecordDialog({
										table: tablename,
										callback: function(data){
											var key = data[keyfld];
											var val = data[valfld];
                                                                                        var $option = $(\'<option value="\'+key+\'">\'+val+\'</option>\');
                                                                                        
											$("#"+fieldname).append($option);
											$("#"+fieldname).val(key);
                                                                                        if ( !val || val === key ){
                                                                                            var q = {
                                                                                                "-action" : "field_vocab_value",
                                                                                                "-key" : key,
                                                                                                "-table" : ' . json_encode($field['tablename']) . ',
                                                                                                "-field" : ' . json_encode($field['name']) . '
                                                                                            };
                                                                                            $.get(DATAFACE_SITE_HREF, q, function(res){
                                                                                                if ( res && res.code === 200 ){
                                                                                                    $option.text(res.value);
                                                                                                }
                                                                                            });
                                                                                        }
											
										}
									});
								});
							});
							</script>
							';
                            $widget['suffix'] = $suffix;
                        }
                    }
                }
            } catch (Exception $ex) {
                error_log($ex->getMessage());
            }
        }
        //$el->setFieldDef($field);
        //return $el;
        return $el;
    }