function symptoms_form($selected_id = "", $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('symptoms');
    if (!$arrPerm[1] && $selected_id == "") {
        return "";
    }
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='symptoms' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='symptoms' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `symptoms` where `id`='" . makeSafe($selected_id) . "'");
        $row = mysql_fetch_array($res);
    } else {
    }
    // code for template based detail view forms
    // open the detail view template
    if (($_POST['dvprint_x'] != '' || $_GET['dvprint_x'] != '') && $selected_id) {
        $templateCode = @implode('', @file('./templates/symptoms_templateDVP.html'));
        $dvprint = true;
    } else {
        $templateCode = @implode('', @file('./templates/symptoms_templateDV.html'));
        $dvprint = false;
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Symptom details', $templateCode);
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<input type="image" src="insert.gif" name="insert" alt="' . $Translation['add new record'] . '" onclick="return validateData();">', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    if ($selected_id) {
        $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<input type="image" src="print.gif" vspace="1" name="dvprint" id="dvprint" alt="' . $Translation['printer friendly view'] . '" onclick="document.myform.reset(); return true;" style="margin-bottom: 20px;">', $templateCode);
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<input type="image" src="update.gif" vspace="1" name="update" alt="' . $Translation['update record'] . '" onclick="return validateData();">', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
            // set records to read only if user can't insert new records
            if (!$arrPerm[1]) {
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('id').length){ document.getElementsByName('id')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('name').length){ document.getElementsByName('name')[0].readOnly=true; }\n";
                $noUploads = true;
            }
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<input type="image" src="delete.gif" vspace="1" name="delete" alt="' . $Translation['delete record'] . '" onClick="return confirm(\'' . $Translation['are you sure?'] . '\');">', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', "<input type=image src=deselect.gif vspace=1 name=deselect alt=\"" . $Translation['deselect record'] . "\" onclick=\"document.myform.reset(); return true;\">", $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? "<input type=image src=cancel.gif vspace=1 name=deselect alt=\"" . $Translation['deselect record'] . "\" onclick=\"document.myform.reset(); return true;\">" : '', $templateCode);
    }
    // process combos
    // process foreign key links
    if ($selected_id) {
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(comments)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', htmlspecialchars($row['name'], ENT_QUOTES), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" cols="50" rows="5" class="TextBox">' . htmlspecialchars($row['description'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', $row['description'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(description)%%>', $row['description'], $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" cols="50" rows="5" class="TextBox">' . htmlspecialchars($row['comments'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(comments)%%>', $row['comments'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(comments)%%>', $row['comments'], $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" cols="50" rows="5" class="TextBox"></textarea>', $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" cols="50" rows="5" class="TextBox"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!--', $templateCode);
    $templateCode = str_replace('%%>', '-->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tif(document.getElementById('" . $name . "_link')!=undefined){\n";
            $templateCode .= "\t\tdocument.getElementById('" . $name . "_link').style.visibility='visible';\n";
            $templateCode .= "\t}\n";
            for ($i = 1; $i < 10; $i++) {
                $templateCode .= "\tif(document.getElementById('" . $name . "_plink{$i}')!=undefined){\n";
                $templateCode .= "\t\tdocument.getElementById('" . $name . "_plink{$i}').style.visibility='visible';\n";
                $templateCode .= "\t}\n";
            }
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n\tfunction validateData(){";
        $templateCode .= "\n\t\tif(\$F('name')==''){ alert('" . addslashes($Translation['error:']) . ' "Name": ' . addslashes($Translation['field not null']) . "'); \$('name').focus(); return false; }";
        $templateCode .= "\n\t\treturn true;";
        $templateCode .= "\n\t}";
        $templateCode .= "\n</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: symptoms_dv
    if (function_exists('symptoms_dv')) {
        $args = array();
        symptoms_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function NavMenus()
{
    global $Translation;
    $t = time();
    $menu = "<select name=nav_menu onChange='window.location=document.myform.nav_menu.options[document.myform.nav_menu.selectedIndex].value;'>";
    $menu .= "<option value='#' class=SelectedOption style='color:black;'>" . $Translation["select a table"] . "</option>";
    $menu .= "<option value='index.php' class=SelectedOption style='color:black;'>" . $Translation["homepage"] . "</option>";
    if (getLoggedAdmin()) {
        $menu .= "<option value='admin/' class=SelectedOption style='color:red;'>" . $Translation['admin area'] . "</option>";
    }
    $arrTables = getTableList();
    if (is_array($arrTables)) {
        foreach ($arrTables as $tn => $tc) {
            $tChk = array_search($tn, array());
            if ($tChk !== false && $tChk !== null) {
                $searchFirst = '&Filter_x=1';
            } else {
                $searchFirst = '';
            }
            $menu .= "<option value='" . $tn . "_view.php?t={$t}{$searchFirst}' class=SelectedOption>{$tc['0']}</option>";
        }
    }
    $menu .= "</select>";
    return $menu;
}
Esempio n. 3
0
 /**
  * データソースを指定してモデルリストを取得する
  * 
  * @param string $configKeyName データソース名
  * @return array
  */
 public function getListModels($type = 'core')
 {
     $db = ConnectionManager::getDataSource('default');
     $listSources = $db->listSources();
     if (!$listSources) {
         return array();
     }
     $tableList = getTableList();
     $sources = array();
     foreach ($listSources as $source) {
         if (in_array($source, $tableList[$type])) {
             $sources[] = $source;
         }
     }
     return $sources;
 }
Esempio n. 4
0
function getHandleTableList()
{
    $s = '';
    $lableStr = '';
    $lableStr = '表列表[' . @$_REQUEST['mdbpath'] . ']';
    if ($GLOBALS['WEB_CACHEContent'] == '') {
        $GLOBALS['WEB_CACHEContent'] = getFText($GLOBALS['WEB_CACHEFile']);
    }
    $s = getConfigContentBlock($GLOBALS['WEB_CACHEContent'], '#' . $lableStr . '#');
    if ($s == '') {
        $s = lCase(getTableList());
        $s = '|' . replace($s, vbCrlf(), '|') . '|';
        $GLOBALS['WEB_CACHEContent'] = setConfigFileBlock($GLOBALS['WEB_CACHEFile'], $s, '#' . $lableStr . '#');
        if ($GLOBALS['isCacheTip'] == true) {
            aspEcho('缓冲', $lableStr);
        }
    }
    $getHandleTableList = $s;
    return @$getHandleTableList;
}
function residence_and_rental_history_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('residence_and_rental_history');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_tenant = thisOr(undo_magic_quotes($_REQUEST['filterer_tenant']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: tenant
    $combo_tenant = new DataCombo();
    // combobox: duration_of_residency_from
    $combo_duration_of_residency_from = new DateCombo();
    $combo_duration_of_residency_from->DateFormat = "mdy";
    $combo_duration_of_residency_from->MinYear = 1900;
    $combo_duration_of_residency_from->MaxYear = 2100;
    $combo_duration_of_residency_from->DefaultDate = parseMySQLDate('', '');
    $combo_duration_of_residency_from->MonthNames = $Translation['month names'];
    $combo_duration_of_residency_from->NamePrefix = 'duration_of_residency_from';
    // combobox: to
    $combo_to = new DateCombo();
    $combo_to->DateFormat = "mdy";
    $combo_to->MinYear = 1900;
    $combo_to->MaxYear = 2100;
    $combo_to->DefaultDate = parseMySQLDate('', '');
    $combo_to->MonthNames = $Translation['month names'];
    $combo_to->NamePrefix = 'to';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='residence_and_rental_history' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='residence_and_rental_history' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `residence_and_rental_history` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_tenant->SelectedData = $row['tenant'];
        $combo_duration_of_residency_from->DefaultDate = $row['duration_of_residency_from'];
        $combo_to->DefaultDate = $row['to'];
    } else {
        $combo_tenant->SelectedData = $filterer_tenant;
    }
    $combo_tenant->HTML = '<span id="tenant-container' . $rnd1 . '"></span><input type="hidden" name="tenant" id="tenant' . $rnd1 . '">';
    $combo_tenant->MatchText = '<span id="tenant-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenant" id="tenant' . $rnd1 . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_tenant__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['tenant'] : $filterer_tenant);
    ?>
"};

		jQuery(function() {
			tenant_reload__RAND__();
		});
		function tenant_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#tenant-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_tenant__RAND__.value, t: 'residence_and_rental_history', f: 'tenant' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="tenant"]').val(resp.results[0].id);
						jQuery('[id=tenant-container-readonly__RAND__]').html('<span id="tenant-match-text">' + resp.results[0].text + '</span>');


						if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'residence_and_rental_history', f: 'tenant' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_tenant__RAND__.value = e.added.id;
				current_tenant__RAND__.text = e.added.text;
				jQuery('[name="tenant"]').val(e.added.id);


				if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_tenant__RAND__.value, t: 'residence_and_rental_history', f: 'tenant' }
			}).done(function(resp){
				jQuery('[id=tenant-container__RAND__], [id=tenant-container-readonly__RAND__]').html('<span id="tenant-match-text">' + resp.results[0].text + '</span>');

				if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/residence_and_rental_history_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/residence_and_rental_history_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Residence and rental history details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return residence_and_rental_history_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return residence_and_rental_history_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return residence_and_rental_history_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#tenant').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#tenant_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#address').replaceWith('<p class=\"form-control-static\" id=\"address\">' + (jQuery('#address').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#landlord_or_manager_name').replaceWith('<p class=\"form-control-static\" id=\"landlord_or_manager_name\">' + (jQuery('#landlord_or_manager_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#landlord_or_manager_phone').replaceWith('<p class=\"form-control-static\" id=\"landlord_or_manager_phone\">' + (jQuery('#landlord_or_manager_phone').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#monthly_rent').replaceWith('<p class=\"form-control-static\" id=\"monthly_rent\">' + (jQuery('#monthly_rent').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#duration_of_residency_from').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#duration_of_residency_fromDay, #duration_of_residency_fromMonth, #duration_of_residency_fromYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#to').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#toDay, #toMonth, #toYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#reason_for_leaving').replaceWith('<p class=\"form-control-static\" id=\"reason_for_leaving\">' + (jQuery('#reason_for_leaving').val() || '') + '</p>');\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(tenant)%%>', $combo_tenant->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(tenant)%%>', $combo_tenant->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(tenant)%%>', urlencode($combo_tenant->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(duration_of_residency_from)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_duration_of_residency_from->GetHTML(true) . '</p>' : $combo_duration_of_residency_from->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(duration_of_residency_from)%%>', $combo_duration_of_residency_from->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(to)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_to->GetHTML(true) . '</p>' : $combo_to->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(to)%%>', $combo_to->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(tenant)%%>', $combo_tenant->SelectedData ? "<span id=\"applicants_and_tenants_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"applicants_and_tenants_view.php?SelectedID=" . urlencode($combo_tenant->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(tenant)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(landlord_or_manager_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(landlord_or_manager_phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(monthly_rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(duration_of_residency_from)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(to)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reason_for_leaving)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenant)%%>', htmlspecialchars($row['tenant'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenant)%%>', urlencode($urow['tenant']), $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', htmlspecialchars($row['address'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(address)%%>', urlencode($urow['address']), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_name)%%>', htmlspecialchars($row['landlord_or_manager_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_name)%%>', urlencode($urow['landlord_or_manager_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_phone)%%>', htmlspecialchars($row['landlord_or_manager_phone'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_phone)%%>', urlencode($urow['landlord_or_manager_phone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_rent)%%>', htmlspecialchars($row['monthly_rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_rent)%%>', urlencode($urow['monthly_rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(duration_of_residency_from)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['duration_of_residency_from'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duration_of_residency_from)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['duration_of_residency_from'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(to)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['to'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(to)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['to'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(reason_for_leaving)%%>', htmlspecialchars($row['reason_for_leaving'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reason_for_leaving)%%>', urlencode($urow['reason_for_leaving']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . htmlspecialchars($row['notes'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', $row['notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenant)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenant)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(address)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_phone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(duration_of_residency_from)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duration_of_residency_from)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(to)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(to)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reason_for_leaving)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reason_for_leaving)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: residence_and_rental_history_dv
    if (function_exists('residence_and_rental_history_dv')) {
        $args = array();
        residence_and_rental_history_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
<?php

$currDir = dirname(__FILE__);
require "{$currDir}/incCommon.php";
// tables list
$tables = getTableList();
// ensure that a memberID is provided
if ($_GET['memberID'] != '') {
    $memberID = makeSafe(strtolower($_GET['memberID']));
} elseif ($_POST['memberID'] != '') {
    $memberID = makeSafe(strtolower($_POST['memberID']));
} else {
    // error in request. redirect to members page.
    redirect('admin/pageViewMembers.php');
}
// validate memberID exists and is not guest and is not admin
$anonymousMember = strtolower($adminConfig['anonymousMember']);
$anonymousGroup = $adminConfig['anonymousGroup'];
$anonGroupID = sqlValue("select groupID from membership_groups where lcase(name)='" . strtolower(makeSafe($anonymousGroup)) . "'");
$adminGroupID = sqlValue("select groupID from membership_groups where name='Admins'");
$groupID = sqlValue("select groupID from membership_users where lcase(memberID)='{$memberID}'");
$group = sqlValue("select name from membership_groups where groupID='{$groupID}'");
if ($groupID == $anonGroupID || $memberID == $anonymousMember || !$groupID || $groupID == $adminGroupID || $memberID == $adminConfig['adminUsername']) {
    // error in request. redirect to members page.
    redirect('admin/pageViewMembers.php');
}
// request to save changes?
if ($_POST['saveChanges'] != '') {
    // validate data
    foreach ($tables as $t => $tc) {
        eval(" \n\t\t\t\t\${$t}_insert=checkPermissionVal('{$t}_insert');\n\t\t\t\t\${$t}_view=checkPermissionVal('{$t}_view');\n\t\t\t\t\${$t}_edit=checkPermissionVal('{$t}_edit');\n\t\t\t\t\${$t}_delete=checkPermissionVal('{$t}_delete');\n\t\t\t");
function units_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('units');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: property
    $combo_property = new DataCombo();
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Occupied;;Listed;;Unlisted")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    // combobox: features
    $combo_features = new Combo();
    $combo_features->ListType = 3;
    $combo_features->MultipleSeparator = ', ';
    $combo_features->ListBoxHeight = 10;
    $combo_features->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.features.csv')) {
        $features_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.features.csv')));
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($features_data)));
        $combo_features->ListData = $combo_features->ListItem;
    } else {
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Cable ready;; Micorwave;;Hardwood floors;; High speed internet;;Air conditioning;;Refrigerator;;Dishwasher;;Walk-in closets;;Balcony;;Deck;;Patio;;Garage parking;;Carport;;Fenced yard;;Laundry room / hookups;; Fireplace;;Oven / range;;Heat - electric;; Heat - gas;; Heat - oil")));
        $combo_features->ListData = $combo_features->ListItem;
    }
    $combo_features->SelectName = 'features';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='units' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='units' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `units` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_property->SelectedData = $row['property'];
        $combo_status->SelectedData = $row['status'];
        $combo_features->SelectedData = $row['features'];
    } else {
        $combo_property->SelectedData = $filterer_property;
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '5' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_status->Render();
    $combo_features->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_property__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['property'] : $filterer_property);
    ?>
"};

		jQuery(function() {
			property_reload__RAND__();
		});
		function property_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="property"]').val(resp.results[0].id);
						jQuery('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');


						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'units', f: 'property' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_property__RAND__.value = e.added.id;
				current_property__RAND__.text = e.added.text;
				jQuery('[name="property"]').val(e.added.id);


				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
			}).done(function(resp){
				jQuery('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/units_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/units_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Unit details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return units_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#unit_number').replaceWith('<p class=\"form-control-static\" id=\"unit_number\">' + (jQuery('#unit_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#size').replaceWith('<p class=\"form-control-static\" id=\"size\">' + (jQuery('#size').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#rooms').replaceWith('<p class=\"form-control-static\" id=\"rooms\">' + (jQuery('#rooms').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#bathroom').replaceWith('<p class=\"form-control-static\" id=\"bathroom\">' + (jQuery('#bathroom').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#features').replaceWith('<p class=\"form-control-static\" id=\"features\">' + (jQuery('#features').val() || '') + '</p>'); jQuery('#features-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#s2id_features').remove();\n";
        $jsReadOnly .= "\tjQuery('#rental_amount').replaceWith('<p class=\"form-control-static\" id=\"rental_amount\">' + (jQuery('#rental_amount').val() || '') + '</p>');\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(features)%%>', $combo_features->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(features)%%>', $combo_features->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(property)%%>', $combo_property->SelectedData ? "<span id=\"properties_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"properties_view.php?SelectedID=" . urlencode($combo_property->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(unit_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(size)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rooms)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(bathroom)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(features)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(market_rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rental_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(deposit_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', htmlspecialchars($row['property'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', htmlspecialchars($row['unit_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode($urow['unit_number']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', htmlspecialchars($row['size'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode($urow['size']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', htmlspecialchars($row['rooms'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode($urow['rooms']), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', htmlspecialchars($row['bathroom'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode($urow['bathroom']), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', htmlspecialchars($row['features'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode($urow['features']), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', htmlspecialchars($row['market_rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode($urow['market_rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', htmlspecialchars($row['rental_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode($urow['rental_amount']), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', htmlspecialchars($row['deposit_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode($urow['deposit_amount']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5">' . htmlspecialchars($row['description'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', $row['description'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(description)%%>', nl2br($row['description']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "\tproperty_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id='+encodeURIComponent('" . addslashes($row['property']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id=' + encodeURIComponent(current_property{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('property{$rnd1}').disable(); \$('propertyLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('property{$rnd1}').enable(); " : "\$('property{$rnd1}').disable(); ") . "\$('propertyLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('property_caption') != undefined) \$('property_caption').onchange=property_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: units_dv
    if (function_exists('units_dv')) {
        $args = array();
        units_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 8
0
						</label>
					</div>

					<div class="row">
						<div class="col-sm-offset-3 col-sm-6">
							<button name="signIn" type="submit" id="submit" value="signIn" class="btn btn-primary btn-lg btn-block"><?php 
echo $Translation['sign in'];
?>
</button>
						</div>
					</div>
				</form>
			</div>

			<?php 
if (is_array(getTableList()) && count(getTableList())) {
    /* if anon. users can see any tables ... */
    ?>
				<div class="panel-footer">
					<?php 
    echo $Translation['browse as guest'];
    ?>
				</div>
			<?php 
}
?>

		</div>
	</div>
</div>
Esempio n. 9
0
$results_per_page = 50;
$id = false;
if (isset($_REQUEST['id'])) {
    $id = iconv('UTF-8', datalist_db_encoding, $_REQUEST['id']);
}
$search_term = false;
if (isset($_REQUEST['s'])) {
    $search_term = iconv('UTF-8', datalist_db_encoding, $_REQUEST['s']);
}
$page = intval($_REQUEST['p']);
if ($page < 1) {
    $page = 1;
}
$skip = $results_per_page * ($page - 1);
$table_name = $_REQUEST['t'];
if (!in_array($table_name, array_keys(getTableList()))) {
    /* invalid table */
    echo '{"results":[{"id":"","text":"Invalid table"}],"more":false,"elapsed":0}';
    exit;
}
/* if id is provided, get owner */
$owner = false;
if ($id) {
    $owner = sqlValue("select memberID from membership_userrecords where tableName='{$table_name}' and pkValue='" . makeSafe($id) . "'");
}
$prepared_data = array();
$where = "g.name!='{$adminConfig['anonymousGroup']}' and p.allowView>0 ";
if ($search_term) {
    $search_term = makeSafe($search_term);
    $where .= "and (u.memberID like '%{$search_term}%' or g.name like '%{$search_term}%')";
}
Esempio n. 10
0
function orders_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('orders');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_CustomerID = thisOr(undo_magic_quotes($_REQUEST['filterer_CustomerID']), '');
    $filterer_EmployeeID = thisOr(undo_magic_quotes($_REQUEST['filterer_EmployeeID']), '');
    $filterer_ShipVia = thisOr(undo_magic_quotes($_REQUEST['filterer_ShipVia']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: CustomerID
    $combo_CustomerID = new DataCombo();
    // combobox: EmployeeID
    $combo_EmployeeID = new DataCombo();
    // combobox: OrderDate
    $combo_OrderDate = new DateCombo();
    $combo_OrderDate->DateFormat = "mdy";
    $combo_OrderDate->MinYear = 1900;
    $combo_OrderDate->MaxYear = 2100;
    $combo_OrderDate->DefaultDate = parseMySQLDate('1', '1');
    $combo_OrderDate->MonthNames = $Translation['month names'];
    $combo_OrderDate->NamePrefix = 'OrderDate';
    // combobox: RequiredDate
    $combo_RequiredDate = new DateCombo();
    $combo_RequiredDate->DateFormat = "mdy";
    $combo_RequiredDate->MinYear = 1900;
    $combo_RequiredDate->MaxYear = 2100;
    $combo_RequiredDate->DefaultDate = parseMySQLDate('1', '1');
    $combo_RequiredDate->MonthNames = $Translation['month names'];
    $combo_RequiredDate->NamePrefix = 'RequiredDate';
    // combobox: ShippedDate
    $combo_ShippedDate = new DateCombo();
    $combo_ShippedDate->DateFormat = "mdy";
    $combo_ShippedDate->MinYear = 1900;
    $combo_ShippedDate->MaxYear = 2100;
    $combo_ShippedDate->DefaultDate = parseMySQLDate('', '');
    $combo_ShippedDate->MonthNames = $Translation['month names'];
    $combo_ShippedDate->NamePrefix = 'ShippedDate';
    // combobox: ShipVia
    $combo_ShipVia = new DataCombo();
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='orders' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='orders' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `orders` where `OrderID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_CustomerID->SelectedData = $row['CustomerID'];
        $combo_EmployeeID->SelectedData = $row['EmployeeID'];
        $combo_OrderDate->DefaultDate = $row['OrderDate'];
        $combo_RequiredDate->DefaultDate = $row['RequiredDate'];
        $combo_ShippedDate->DefaultDate = $row['ShippedDate'];
        $combo_ShipVia->SelectedData = $row['ShipVia'];
    } else {
        $combo_CustomerID->SelectedData = $filterer_CustomerID;
        $combo_EmployeeID->SelectedData = $filterer_EmployeeID;
        $combo_ShipVia->SelectedData = $filterer_ShipVia;
    }
    $combo_CustomerID->HTML = '<span id="CustomerID-container' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . htmlspecialchars($combo_CustomerID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_CustomerID->MatchText = '<span id="CustomerID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . htmlspecialchars($combo_CustomerID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_EmployeeID->HTML = '<span id="EmployeeID-container' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . htmlspecialchars($combo_EmployeeID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_EmployeeID->MatchText = '<span id="EmployeeID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . htmlspecialchars($combo_EmployeeID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_ShipVia->HTML = '<span id="ShipVia-container' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . htmlspecialchars($combo_ShipVia->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_ShipVia->MatchText = '<span id="ShipVia-container-readonly' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . htmlspecialchars($combo_ShipVia->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_CustomerID__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['CustomerID'] : $filterer_CustomerID);
    ?>
"};
		var current_EmployeeID__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['EmployeeID'] : $filterer_EmployeeID);
    ?>
"};
		var current_ShipVia__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['ShipVia'] : $filterer_ShipVia);
    ?>
"};

		jQuery(function() {
			if(typeof(CustomerID_reload__RAND__) == 'function') CustomerID_reload__RAND__();
			if(typeof(EmployeeID_reload__RAND__) == 'function') EmployeeID_reload__RAND__();
			if(typeof(ShipVia_reload__RAND__) == 'function') ShipVia_reload__RAND__();
		});
		function CustomerID_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#CustomerID-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_CustomerID__RAND__.value, t: 'orders', f: 'CustomerID' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="CustomerID"]').val(resp.results[0].id);
						jQuery('[id=CustomerID-container-readonly__RAND__]').html('<span id="CustomerID-match-text">' + resp.results[0].text + '</span>');


						if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'CustomerID' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_CustomerID__RAND__.value = e.added.id;
				current_CustomerID__RAND__.text = e.added.text;
				jQuery('[name="CustomerID"]').val(e.added.id);


				if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_update_autofills__RAND__();
			});

			if(!$j("#CustomerID-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: current_CustomerID__RAND__.value, t: 'orders', f: 'CustomerID' }
				}).done(function(resp){
					$j('[name="CustomerID"]').val(resp.results[0].id);
					$j('[id=CustomerID-container-readonly__RAND__]').html('<span id="CustomerID-match-text">' + resp.results[0].text + '</span>');

					if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_update_autofills__RAND__();
				});
			}

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_CustomerID__RAND__.value, t: 'orders', f: 'CustomerID' }
			}).done(function(resp){
				jQuery('[id=CustomerID-container__RAND__], [id=CustomerID-container-readonly__RAND__]').html('<span id="CustomerID-match-text">' + resp.results[0].text + '</span>');

				if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function EmployeeID_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#EmployeeID-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_EmployeeID__RAND__.value, t: 'orders', f: 'EmployeeID' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="EmployeeID"]').val(resp.results[0].id);
						jQuery('[id=EmployeeID-container-readonly__RAND__]').html('<span id="EmployeeID-match-text">' + resp.results[0].text + '</span>');


						if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'EmployeeID' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_EmployeeID__RAND__.value = e.added.id;
				current_EmployeeID__RAND__.text = e.added.text;
				jQuery('[name="EmployeeID"]').val(e.added.id);


				if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_update_autofills__RAND__();
			});

			if(!$j("#EmployeeID-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: current_EmployeeID__RAND__.value, t: 'orders', f: 'EmployeeID' }
				}).done(function(resp){
					$j('[name="EmployeeID"]').val(resp.results[0].id);
					$j('[id=EmployeeID-container-readonly__RAND__]').html('<span id="EmployeeID-match-text">' + resp.results[0].text + '</span>');

					if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_update_autofills__RAND__();
				});
			}

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_EmployeeID__RAND__.value, t: 'orders', f: 'EmployeeID' }
			}).done(function(resp){
				jQuery('[id=EmployeeID-container__RAND__], [id=EmployeeID-container-readonly__RAND__]').html('<span id="EmployeeID-match-text">' + resp.results[0].text + '</span>');

				if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function ShipVia_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#ShipVia-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_ShipVia__RAND__.value, t: 'orders', f: 'ShipVia' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="ShipVia"]').val(resp.results[0].id);
						jQuery('[id=ShipVia-container-readonly__RAND__]').html('<span id="ShipVia-match-text">' + resp.results[0].text + '</span>');


						if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'ShipVia' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_ShipVia__RAND__.value = e.added.id;
				current_ShipVia__RAND__.text = e.added.text;
				jQuery('[name="ShipVia"]').val(e.added.id);


				if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_update_autofills__RAND__();
			});

			if(!$j("#ShipVia-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: current_ShipVia__RAND__.value, t: 'orders', f: 'ShipVia' }
				}).done(function(resp){
					$j('[name="ShipVia"]').val(resp.results[0].id);
					$j('[id=ShipVia-container-readonly__RAND__]').html('<span id="ShipVia-match-text">' + resp.results[0].text + '</span>');

					if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_update_autofills__RAND__();
				});
			}

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_ShipVia__RAND__.value, t: 'orders', f: 'ShipVia' }
			}).done(function(resp){
				jQuery('[id=ShipVia-container__RAND__], [id=ShipVia-container-readonly__RAND__]').html('<span id="ShipVia-match-text">' + resp.results[0].text + '</span>');

				if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/orders_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/orders_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#CustomerID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#CustomerID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#EmployeeID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#EmployeeID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#OrderDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#OrderDateDay, #OrderDateMonth, #OrderDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#RequiredDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#RequiredDateDay, #RequiredDateMonth, #RequiredDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShippedDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#ShippedDateDay, #ShippedDateMonth, #ShippedDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShipVia').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShipVia_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#Freight').replaceWith('<div class=\"form-control-static\" id=\"Freight\">' + (jQuery('#Freight').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(CustomerID)%%>', $combo_CustomerID->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(CustomerID)%%>', $combo_CustomerID->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(CustomerID)%%>', urlencode($combo_CustomerID->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(EmployeeID)%%>', $combo_EmployeeID->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(EmployeeID)%%>', $combo_EmployeeID->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(EmployeeID)%%>', urlencode($combo_EmployeeID->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(OrderDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_OrderDate->GetHTML(true) . '</div>' : $combo_OrderDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(OrderDate)%%>', $combo_OrderDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(RequiredDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_RequiredDate->GetHTML(true) . '</div>' : $combo_RequiredDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(RequiredDate)%%>', $combo_RequiredDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(ShippedDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_ShippedDate->GetHTML(true) . '</div>' : $combo_ShippedDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(ShippedDate)%%>', $combo_ShippedDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(ShipVia)%%>', $combo_ShipVia->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(ShipVia)%%>', $combo_ShipVia->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(ShipVia)%%>', urlencode($combo_ShipVia->MatchText), $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array('CustomerID' => array('customers', 'Customer'), 'EmployeeID' => array('employees', 'Employee'), 'ShipVia' => array('shippers', 'Ship Via'));
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(OrderID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(CustomerID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(EmployeeID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(OrderDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(RequiredDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ShippedDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ShipVia)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Freight)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(OrderID)%%>', htmlspecialchars($row['OrderID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode($urow['OrderID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', htmlspecialchars($row['CustomerID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode($urow['CustomerID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', htmlspecialchars($row['EmployeeID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode($urow['EmployeeID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(OrderDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['OrderDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['OrderDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(RequiredDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['RequiredDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['RequiredDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShippedDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['ShippedDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['ShippedDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShipVia)%%>', htmlspecialchars($row['ShipVia'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode($urow['ShipVia']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Freight)%%>', htmlspecialchars($row['Freight'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode($urow['Freight']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(OrderID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(OrderDate)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(RequiredDate)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShippedDate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShipVia)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Freight)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode('0'), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "\tCustomerID_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'orders_autofill.php?rnd1={$rnd1}&mfk=CustomerID&id='+encodeURIComponent('" . addslashes($row['CustomerID']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'iso-8859-1', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'orders_autofill.php?rnd1={$rnd1}&mfk=CustomerID&id=' + encodeURIComponent(current_CustomerID{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'iso-8859-1', method: 'get', onCreate: function(){ \$('CustomerID{$rnd1}').disable(); \$('CustomerIDLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('CustomerID{$rnd1}').enable(); " : "\$('CustomerID{$rnd1}').disable(); ") . "\$('CustomerIDLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('CustomerID_caption') != undefined) \$('CustomerID_caption').onchange=CustomerID_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: orders_dv
    if (function_exists('orders_dv')) {
        $args = array();
        orders_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 11
0
/**
 * return error message as string, or true indicating success
 * requires setup to be written first.
 */
function setup_database()
{
    $conn = DB_Helper::getInstance(false);
    $db_exists = checkDatabaseExists($conn, $_POST['db_name']);
    if (!$db_exists) {
        if (@$_POST['create_db'] == 'yes') {
            try {
                $conn->query("CREATE DATABASE {{{$_POST['db_name']}}}");
            } catch (DbException $e) {
                throw new RuntimeException(getErrorMessage('create_db', $e->getMessage()));
            }
        } else {
            throw new RuntimeException('The provided database name could not be found. Review your information or specify that the database should be created in the form below.');
        }
    }
    // create the new user, if needed
    if (@$_POST['alternate_user'] == 'yes') {
        $user_list = getUserList($conn);
        if ($user_list) {
            $user_exists = in_array(strtolower(@$_POST['eventum_user']), $user_list);
            if (@$_POST['create_user'] == 'yes') {
                if (!$user_exists) {
                    $stmt = "GRANT SELECT, UPDATE, DELETE, INSERT, ALTER, DROP, CREATE, INDEX ON {{{$_POST['db_name']}}}.* TO ?@'%' IDENTIFIED BY ?";
                    try {
                        $conn->query($stmt, array($_POST['eventum_user'], $_POST['eventum_password']));
                    } catch (DbException $e) {
                        throw new RuntimeException(getErrorMessage('create_user', $e->getMessage()));
                    }
                }
            } else {
                if (!$user_exists) {
                    throw new RuntimeException('The provided MySQL username could not be found. Review your information or specify that the username should be created in the form below.');
                }
            }
        }
    }
    // check if we can use the database
    try {
        $conn->query("USE {{{$_POST['db_name']}}}");
    } catch (DbException $e) {
        throw new RuntimeException(getErrorMessage('select_db', $e->getMessage()));
    }
    // set sql mode (sad that we rely on old bad mysql defaults)
    $conn->query("SET SQL_MODE = ''");
    // check the CREATE and DROP privileges by trying to create and drop a test table
    $table_list = getTableList($conn);
    if (!in_array('eventum_test', $table_list)) {
        try {
            $conn->query('CREATE TABLE eventum_test (test char(1))');
        } catch (DbException $e) {
            throw new RuntimeException(getErrorMessage('create_test', $e->getMessage()));
        }
    }
    try {
        $conn->query('DROP TABLE eventum_test');
    } catch (DbException $e) {
        throw new RuntimeException(getErrorMessage('drop_test', $e->getMessage()));
    }
    // if requested. drop tables first
    if (@$_POST['drop_tables'] == 'yes') {
        $queries = get_queries(APP_PATH . '/upgrade/drop.sql');
        foreach ($queries as $stmt) {
            try {
                $conn->query($stmt);
            } catch (DbException $e) {
                throw new RuntimeException(getErrorMessage('drop_table', $e->getMessage()));
            }
        }
    }
    // setup database with upgrade script
    $buffer = array();
    try {
        $dbmigrate = new DbMigrate(APP_PATH . '/upgrade');
        $dbmigrate->setLogger(function ($e) use(&$buffer) {
            $buffer[] = $e;
        });
        $dbmigrate->patch_database();
        $e = false;
    } catch (Exception $e) {
    }
    global $tpl;
    $tpl->assign('db_result', implode("\n", $buffer));
    if ($e) {
        $upgrade_script = APP_PATH . '/upgrade/update-database.php';
        $error = array('Database setup failed on upgrade:', "<tt>{$e->getMessage()}</tt>", '', "You may want run update script <tt>{$upgrade_script}</tt> manually");
        throw new RuntimeException(implode('<br/>', $error));
    }
    // write db name now that it has been created
    $setup = array();
    $setup['database'] = $_POST['db_name'];
    // substitute the appropriate values in config.php!!!
    if (@$_POST['alternate_user'] == 'yes') {
        $setup['username'] = $_POST['eventum_user'];
        $setup['password'] = $_POST['eventum_password'];
    }
    Setup::save(array('database' => $setup));
}
Esempio n. 12
0
function submitlog_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('submitlog');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: pdate
    $combo_pdate = new DateCombo();
    $combo_pdate->DateFormat = "mdy";
    $combo_pdate->MinYear = 1900;
    $combo_pdate->MaxYear = 2100;
    $combo_pdate->DefaultDate = parseMySQLDate('', '');
    $combo_pdate->MonthNames = $Translation['month names'];
    $combo_pdate->NamePrefix = 'pdate';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='submitlog' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='submitlog' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `submitlog` where `submid`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_pdate->DefaultDate = $row['pdate'];
    } else {
    }
    // code for template based detail view forms
    // open the detail view template
    $templateCode = @file_get_contents('./templates/submitlog_templateDV.html');
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Filtered Submissions', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return submitlog_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return submitlog_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return submitlog_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#cstatus').prop('disabled', true);\n";
        $jsReadOnly .= "\tjQuery('#logtime').replaceWith('<div class=\"form-control-static\" id=\"logtime\">' + (jQuery('#logtime').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ipaddr').replaceWith('<div class=\"form-control-static\" id=\"ipaddr\">' + (jQuery('#ipaddr').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#company').replaceWith('<div class=\"form-control-static\" id=\"company\">' + (jQuery('#company').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#country').replaceWith('<div class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#website').replaceWith('<div class=\"form-control-static\" id=\"website\">' + (jQuery('#website').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#website, #website-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#contactname').replaceWith('<div class=\"form-control-static\" id=\"contactname\">' + (jQuery('#contactname').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#email').replaceWith('<div class=\"form-control-static\" id=\"email\">' + (jQuery('#email').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#title').replaceWith('<div class=\"form-control-static\" id=\"title\">' + (jQuery('#title').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#version').replaceWith('<div class=\"form-control-static\" id=\"version\">' + (jQuery('#version').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#pdate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#pdateDay, #pdateMonth, #pdateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#cost').replaceWith('<div class=\"form-control-static\" id=\"cost\">' + (jQuery('#cost').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ptype').replaceWith('<div class=\"form-control-static\" id=\"ptype\">' + (jQuery('#ptype').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#install').replaceWith('<div class=\"form-control-static\" id=\"install\">' + (jQuery('#install').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#os').replaceWith('<div class=\"form-control-static\" id=\"os\">' + (jQuery('#os').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#languages').replaceWith('<div class=\"form-control-static\" id=\"languages\">' + (jQuery('#languages').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#changeinfo').replaceWith('<div class=\"form-control-static\" id=\"changeinfo\">' + (jQuery('#changeinfo').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#category').replaceWith('<div class=\"form-control-static\" id=\"category\">' + (jQuery('#category').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#requirements').replaceWith('<div class=\"form-control-static\" id=\"requirements\">' + (jQuery('#requirements').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ksize').replaceWith('<div class=\"form-control-static\" id=\"ksize\">' + (jQuery('#ksize').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#keywords').replaceWith('<div class=\"form-control-static\" id=\"keywords\">' + (jQuery('#keywords').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<div class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#descrlarge').replaceWith('<div class=\"form-control-static\" id=\"descrlarge\">' + (jQuery('#descrlarge').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#homepage').replaceWith('<div class=\"form-control-static\" id=\"homepage\">' + (jQuery('#homepage').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#screenshot').replaceWith('<div class=\"form-control-static\" id=\"screenshot\">' + (jQuery('#screenshot').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#screenshot, #screenshot-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#icon').replaceWith('<div class=\"form-control-static\" id=\"icon\">' + (jQuery('#icon').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#padfile').replaceWith('<div class=\"form-control-static\" id=\"padfile\">' + (jQuery('#padfile').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#download').replaceWith('<div class=\"form-control-static\" id=\"download\">' + (jQuery('#download').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#aspnumber').replaceWith('<div class=\"form-control-static\" id=\"aspnumber\">' + (jQuery('#aspnumber').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#backlink').replaceWith('<div class=\"form-control-static\" id=\"backlink\">' + (jQuery('#backlink').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#backlink, #backlink-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#affiliate').replaceWith('<div class=\"form-control-static\" id=\"affiliate\">' + (jQuery('#affiliate').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#affiliateid').replaceWith('<div class=\"form-control-static\" id=\"affiliateid\">' + (jQuery('#affiliateid').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(pdate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_pdate->GetHTML(true) . '</div>' : $combo_pdate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(pdate)%%>', $combo_pdate->GetHTML(true), $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array();
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(submid)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(cstatus)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(logtime)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ipaddr)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(website)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(contactname)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(email)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(title)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(version)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(pdate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(cost)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ptype)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(install)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(os)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(languages)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(changeinfo)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(category)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(requirements)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ksize)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(keywords)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(descrlarge)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(homepage)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(screenshot)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(icon)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(padfile)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(download)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(aspnumber)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(backlink)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(affiliate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(affiliateid)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(submid)%%>', htmlspecialchars($row['submid'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(submid)%%>', urlencode($urow['submid']), $templateCode);
        $templateCode = str_replace('<%%CHECKED(cstatus)%%>', $row['cstatus'] ? "checked" : "", $templateCode);
        $templateCode = str_replace('<%%VALUE(logtime)%%>', htmlspecialchars($row['logtime'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(logtime)%%>', urlencode($urow['logtime']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ipaddr)%%>', htmlspecialchars($row['ipaddr'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ipaddr)%%>', urlencode($urow['ipaddr']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company)%%>', htmlspecialchars($row['company'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company)%%>', urlencode($urow['company']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', htmlspecialchars($row['country'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', htmlspecialchars($row['website'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode($urow['website']), $templateCode);
        $templateCode = str_replace('<%%VALUE(contactname)%%>', htmlspecialchars($row['contactname'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(contactname)%%>', urlencode($urow['contactname']), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', htmlspecialchars($row['email'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode($urow['email']), $templateCode);
        $templateCode = str_replace('<%%VALUE(title)%%>', htmlspecialchars($row['title'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(title)%%>', urlencode($urow['title']), $templateCode);
        $templateCode = str_replace('<%%VALUE(version)%%>', htmlspecialchars($row['version'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(version)%%>', urlencode($urow['version']), $templateCode);
        $templateCode = str_replace('<%%VALUE(pdate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['pdate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(pdate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['pdate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(cost)%%>', htmlspecialchars($row['cost'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(cost)%%>', urlencode($urow['cost']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ptype)%%>', htmlspecialchars($row['ptype'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ptype)%%>', urlencode($urow['ptype']), $templateCode);
        $templateCode = str_replace('<%%VALUE(install)%%>', htmlspecialchars($row['install'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(install)%%>', urlencode($urow['install']), $templateCode);
        $templateCode = str_replace('<%%VALUE(os)%%>', htmlspecialchars($row['os'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(os)%%>', urlencode($urow['os']), $templateCode);
        $templateCode = str_replace('<%%VALUE(languages)%%>', htmlspecialchars($row['languages'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(languages)%%>', urlencode($urow['languages']), $templateCode);
        $templateCode = str_replace('<%%VALUE(changeinfo)%%>', htmlspecialchars($row['changeinfo'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(changeinfo)%%>', urlencode($urow['changeinfo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(category)%%>', htmlspecialchars($row['category'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(category)%%>', urlencode($urow['category']), $templateCode);
        $templateCode = str_replace('<%%VALUE(requirements)%%>', htmlspecialchars($row['requirements'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requirements)%%>', urlencode($urow['requirements']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ksize)%%>', htmlspecialchars($row['ksize'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ksize)%%>', urlencode($urow['ksize']), $templateCode);
        $templateCode = str_replace('<%%VALUE(keywords)%%>', htmlspecialchars($row['keywords'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(keywords)%%>', urlencode($urow['keywords']), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(descrlarge)%%>', htmlspecialchars($row['descrlarge'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(descrlarge)%%>', urlencode($urow['descrlarge']), $templateCode);
        $templateCode = str_replace('<%%VALUE(homepage)%%>', htmlspecialchars($row['homepage'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(homepage)%%>', urlencode($urow['homepage']), $templateCode);
        $templateCode = str_replace('<%%VALUE(screenshot)%%>', htmlspecialchars($row['screenshot'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(screenshot)%%>', urlencode($urow['screenshot']), $templateCode);
        $templateCode = str_replace('<%%VALUE(icon)%%>', htmlspecialchars($row['icon'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(icon)%%>', urlencode($urow['icon']), $templateCode);
        $templateCode = str_replace('<%%VALUE(padfile)%%>', htmlspecialchars($row['padfile'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(padfile)%%>', urlencode($urow['padfile']), $templateCode);
        $templateCode = str_replace('<%%VALUE(download)%%>', htmlspecialchars($row['download'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(download)%%>', urlencode($urow['download']), $templateCode);
        $templateCode = str_replace('<%%VALUE(aspnumber)%%>', htmlspecialchars($row['aspnumber'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(aspnumber)%%>', urlencode($urow['aspnumber']), $templateCode);
        $templateCode = str_replace('<%%VALUE(backlink)%%>', htmlspecialchars($row['backlink'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(backlink)%%>', urlencode($urow['backlink']), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliate)%%>', htmlspecialchars($row['affiliate'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliate)%%>', urlencode($urow['affiliate']), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliateid)%%>', htmlspecialchars($row['affiliateid'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliateid)%%>', urlencode($urow['affiliateid']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(submid)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(submid)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%CHECKED(cstatus)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(logtime)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(logtime)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ipaddr)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ipaddr)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(contactname)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(contactname)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(email)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(email)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(title)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(title)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(version)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(version)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(pdate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(pdate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(cost)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(cost)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ptype)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ptype)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(install)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(install)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(os)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(os)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(languages)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(languages)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(changeinfo)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(changeinfo)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(category)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(category)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(requirements)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(requirements)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ksize)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ksize)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(keywords)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(keywords)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(descrlarge)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(descrlarge)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(homepage)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(homepage)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(screenshot)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(screenshot)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(icon)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(icon)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(padfile)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(padfile)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(download)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(download)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(aspnumber)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(aspnumber)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(backlink)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(backlink)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(affiliateid)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(affiliateid)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_REQUEST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
            $templateCode .= "\n\tif(document.getElementById('websiteEdit')){ document.getElementById('websiteEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('websiteEditLink')){ document.getElementById('websiteEditLink').style.display='none'; }";
            $templateCode .= "\n\tif(document.getElementById('screenshotEdit')){ document.getElementById('screenshotEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('screenshotEditLink')){ document.getElementById('screenshotEditLink').style.display='none'; }";
            $templateCode .= "\n\tif(document.getElementById('backlinkEdit')){ document.getElementById('backlinkEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('backlinkEditLink')){ document.getElementById('backlinkEditLink').style.display='none'; }";
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: submitlog_dv
    if (function_exists('submitlog_dv')) {
        $args = array();
        submitlog_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 13
0
 /**
  * バックアップファイルを書きだす
  *
  * @param string $configKeyName
  * @param string $path
  * @return boolean
  */
 protected function _writeBackup($path, $plugin = '')
 {
     $db = ConnectionManager::getDataSource('default');
     $db->cacheSources = false;
     $tables = $db->listSources();
     $tableList = getTableList();
     foreach ($tables as $table) {
         if (!$plugin && in_array($table, $tableList['core']) || $plugin && in_array($table, $tableList['plugin'])) {
             $table = str_replace($db->config['prefix'], '', $table);
             $model = Inflector::classify(Inflector::singularize($table));
             if (!$db->writeSchema(array('path' => $path, 'model' => $model, 'plugin' => $plugin))) {
                 return false;
             }
             if (!$db->writeCsv(array('path' => $path . $table . '.csv', 'encoding' => 'SJIS'))) {
                 return false;
             }
         }
     }
     return true;
 }
Esempio n. 14
0
function NavMenus($options = array())
{
    global $Translation;
    $menu = '';
    /* default options */
    if (empty($options)) {
        $options = array('tabs' => 7);
    }
    $t = time();
    $arrTables = getTableList();
    if (is_array($arrTables)) {
        foreach ($arrTables as $tn => $tc) {
            /* ---- list of tables where hide link in nav menu is set ---- */
            $tChkHL = array_search($tn, array('order_details'));
            if ($tChkHL !== false && $tChkHL !== null) {
                continue;
            }
            /* ---- list of tables where filter first is set ---- */
            $tChkFF = array_search($tn, array());
            if ($tChkFF !== false && $tChkFF !== null) {
                $searchFirst = '&Filter_x=1';
            } else {
                $searchFirst = '';
            }
            $menu .= "<li><a href=\"{$tn}_view.php?t={$t}{$searchFirst}\"><img src=\"" . ($tc[2] ? $tc[2] : 'blank.gif') . "\" height=\"32\"> {$tc[0]}</a></li>";
        }
    }
    // custom nav links, as defined in "hooks/links-navmenu.php"
    global $navLinks;
    if (is_array($navLinks)) {
        $memberInfo = getMemberInfo();
        $links_added = 0;
        foreach ($navLinks as $link) {
            if (!isset($link['url']) || !isset($link['title'])) {
                continue;
            }
            if ($memberInfo['admin'] || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
                if (!$links_added) {
                    $menu .= '<li class="divider"></li>';
                }
                $menu .= "<li><a href=\"{$link['url']}\"><img src=\"" . ($link['icon'] ? $link['icon'] : 'blank.gif') . "\" height=\"32\"> {$link['title']}</a></li>";
                $links_added++;
            }
        }
    }
    return $menu;
}
function properties_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('properties');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_owner = thisOr(undo_magic_quotes($_REQUEST['filterer_owner']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: type
    $combo_type = new Combo();
    $combo_type->ListType = 2;
    $combo_type->MultipleSeparator = ', ';
    $combo_type->ListBoxHeight = 10;
    $combo_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.type.csv')) {
        $type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.type.csv')));
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
        $combo_type->ListData = $combo_type->ListItem;
    } else {
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Residential;;Commercial;;Condo/Townhome;;Multi-Family;;Single-Family;;stores;;office;;shops")));
        $combo_type->ListData = $combo_type->ListItem;
    }
    $combo_type->SelectName = 'type';
    $combo_type->AllowNull = false;
    // combobox: owner
    $combo_owner = new DataCombo();
    // combobox: operating_account
    $combo_operating_account = new Combo();
    $combo_operating_account->ListType = 0;
    $combo_operating_account->MultipleSeparator = ', ';
    $combo_operating_account->ListBoxHeight = 10;
    $combo_operating_account->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')) {
        $operating_account_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')));
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($operating_account_data)));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    } else {
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Operating bank account;;Security deposit bank account")));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    }
    $combo_operating_account->SelectName = 'operating_account';
    // combobox: country
    $combo_country = new Combo();
    $combo_country->ListType = 0;
    $combo_country->MultipleSeparator = ', ';
    $combo_country->ListBoxHeight = 10;
    $combo_country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.country.csv')) {
        $country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.country.csv')));
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_data)));
        $combo_country->ListData = $combo_country->ListItem;
    } else {
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country->ListData = $combo_country->ListItem;
    }
    $combo_country->SelectName = 'country';
    // combobox: State
    $combo_State = new Combo();
    $combo_State->ListType = 0;
    $combo_State->MultipleSeparator = ', ';
    $combo_State->ListBoxHeight = 10;
    $combo_State->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.State.csv')) {
        $State_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.State.csv')));
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($State_data)));
        $combo_State->ListData = $combo_State->ListItem;
    } else {
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
        $combo_State->ListData = $combo_State->ListItem;
    }
    $combo_State->SelectName = 'State';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `properties` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_type->SelectedData = $row['type'];
        $combo_owner->SelectedData = $row['owner'];
        $combo_operating_account->SelectedData = $row['operating_account'];
        $combo_country->SelectedData = $row['country'];
        $combo_State->SelectedData = $row['State'];
    } else {
        $combo_type->SelectedText = $_REQUEST['FilterField'][1] == '3' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_owner->SelectedData = $filterer_owner;
        $combo_operating_account->SelectedText = $_REQUEST['FilterField'][1] == '7' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_country->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_State->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_type->Render();
    $combo_owner->HTML = '<span id="owner-container' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_owner->MatchText = '<span id="owner-container-readonly' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_operating_account->Render();
    $combo_country->Render();
    $combo_State->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_owner__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['owner'] : $filterer_owner);
    ?>
"};

		jQuery(function() {
			owner_reload__RAND__();
		});
		function owner_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#owner-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="owner"]').val(resp.results[0].id);
						jQuery('[id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');


						if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'properties', f: 'owner' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_owner__RAND__.value = e.added.id;
				current_owner__RAND__.text = e.added.text;
				jQuery('[name="owner"]').val(e.added.id);


				if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
			}).done(function(resp){
				jQuery('[id=owner-container__RAND__], [id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');

				if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/properties_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/properties_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Property details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return properties_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$AllowInsert || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#property_name').replaceWith('<p class=\"form-control-static\" id=\"property_name\">' + (jQuery('#property_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#number_of_units').replaceWith('<p class=\"form-control-static\" id=\"number_of_units\">' + (jQuery('#number_of_units').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#owner').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#owner_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#country').replaceWith('<p class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</p>'); jQuery('#country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#street').replaceWith('<p class=\"form-control-static\" id=\"street\">' + (jQuery('#street').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<p class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#State').replaceWith('<p class=\"form-control-static\" id=\"State\">' + (jQuery('#State').val() || '') + '</p>'); jQuery('#State-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#ZIP').replaceWith('<p class=\"form-control-static\" id=\"ZIP\">' + (jQuery('#ZIP').val() || '') + '</p>');\n";
        $noUploads = true;
    } elseif ($AllowInsert) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(owner)%%>', $combo_owner->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(owner)%%>', $combo_owner->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(owner)%%>', urlencode($combo_owner->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(operating_account)%%>', $combo_operating_account->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(operating_account)%%>', $combo_operating_account->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country)%%>', $combo_country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country)%%>', $combo_country->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(State)%%>', $combo_State->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(State)%%>', $combo_State->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(owner)%%>', $combo_owner->SelectedData ? "<span id=\"rental_owners_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"rental_owners_view.php?SelectedID=" . urlencode($combo_owner->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(number_of_units)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(owner)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(operating_account)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_reserve)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(lease_term)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(street)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(State)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ZIP)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', htmlspecialchars($row['property_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode($urow['property_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', htmlspecialchars($row['type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', htmlspecialchars($row['number_of_units'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode($urow['number_of_units']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', htmlspecialchars($row['owner'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode($urow['owner']), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', htmlspecialchars($row['operating_account'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode($urow['operating_account']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', htmlspecialchars($row['property_reserve'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode($urow['property_reserve']), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', htmlspecialchars($row['lease_term'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode($urow['lease_term']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', htmlspecialchars($row['country'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', htmlspecialchars($row['street'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode($urow['street']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', htmlspecialchars($row['State'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode($urow['State']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', htmlspecialchars($row['ZIP'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode($urow['ZIP']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: properties_dv
    if (function_exists('properties_dv')) {
        $args = array();
        properties_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 16
0
function entries_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('entries');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_report = thisOr(undo_magic_quotes($_REQUEST['filterer_report']), '');
    $filterer_outcome = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome']), '');
    $filterer_indicator = thisOr(undo_magic_quotes($_REQUEST['filterer_indicator']), '');
    $filterer_beneficiary_group = thisOr(undo_magic_quotes($_REQUEST['filterer_beneficiary_group']), '');
    // populate filterers, starting from children to grand-parents
    if ($filterer_indicator && !$filterer_outcome) {
        $filterer_outcome = sqlValue("select outcome from indicators where indicator_id='" . makeSafe($filterer_indicator) . "'");
    }
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: created
    $combo_created = new DateCombo();
    $combo_created->DateFormat = "dmy";
    $combo_created->MinYear = 1900;
    $combo_created->MaxYear = 2100;
    $combo_created->DefaultDate = parseMySQLDate('<%%creationDate%%>', '<%%creationDate%%>');
    $combo_created->MonthNames = $Translation['month names'];
    $combo_created->NamePrefix = 'created';
    // combobox: report
    $combo_report = new DataCombo();
    // combobox: outcome
    $combo_outcome = new DataCombo();
    // combobox: indicator, filterable by: outcome
    $combo_indicator = new DataCombo();
    // combobox: beneficiary_group
    $combo_beneficiary_group = new DataCombo();
    // combobox: beneficiary_group_relevance
    $combo_beneficiary_group_relevance = new Combo();
    $combo_beneficiary_group_relevance->ListType = 0;
    $combo_beneficiary_group_relevance->MultipleSeparator = ', ';
    $combo_beneficiary_group_relevance->ListBoxHeight = 10;
    $combo_beneficiary_group_relevance->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')) {
        $beneficiary_group_relevance_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')));
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($beneficiary_group_relevance_data)));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    } else {
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    }
    $combo_beneficiary_group_relevance->SelectName = 'beneficiary_group_relevance';
    // combobox: reliability
    $combo_reliability = new Combo();
    $combo_reliability->ListType = 0;
    $combo_reliability->MultipleSeparator = ', ';
    $combo_reliability->ListBoxHeight = 10;
    $combo_reliability->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.reliability.csv')) {
        $reliability_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.reliability.csv')));
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($reliability_data)));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    } else {
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    }
    $combo_reliability->SelectName = 'reliability';
    // combobox: intentionality
    $combo_intentionality = new Combo();
    $combo_intentionality->ListType = 0;
    $combo_intentionality->MultipleSeparator = ', ';
    $combo_intentionality->ListBoxHeight = 10;
    $combo_intentionality->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')) {
        $intentionality_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')));
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($intentionality_data)));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    } else {
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    }
    $combo_intentionality->SelectName = 'intentionality';
    // combobox: equivalence
    $combo_equivalence = new Combo();
    $combo_equivalence->ListType = 0;
    $combo_equivalence->MultipleSeparator = ', ';
    $combo_equivalence->ListBoxHeight = 10;
    $combo_equivalence->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')) {
        $equivalence_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')));
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($equivalence_data)));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    } else {
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    }
    $combo_equivalence->SelectName = 'equivalence';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='entries' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='entries' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `entries` where `entry_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_created->DefaultDate = $row['created'];
        $combo_report->SelectedData = $row['report'];
        $combo_outcome->SelectedData = $row['outcome'];
        $combo_indicator->SelectedData = $row['indicator'];
        $combo_beneficiary_group->SelectedData = $row['beneficiary_group'];
        $combo_beneficiary_group_relevance->SelectedData = $row['beneficiary_group_relevance'];
        $combo_reliability->SelectedData = $row['reliability'];
        $combo_intentionality->SelectedData = $row['intentionality'];
        $combo_equivalence->SelectedData = $row['equivalence'];
    } else {
        $combo_report->SelectedData = $filterer_report;
        $combo_outcome->SelectedData = $filterer_outcome;
        $combo_indicator->SelectedData = $filterer_indicator;
        $combo_beneficiary_group->SelectedData = $filterer_beneficiary_group;
        $combo_beneficiary_group_relevance->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_reliability->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_intentionality->SelectedText = $_REQUEST['FilterField'][1] == '14' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_equivalence->SelectedText = $_REQUEST['FilterField'][1] == '15' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_report->HTML = $combo_report->MatchText = '<span id="report-container' . $rnd1 . '"></span><input type="hidden" name="report" id="report' . $rnd1 . '">';
    $combo_outcome->HTML = $combo_outcome->MatchText = '<span id="outcome-container' . $rnd1 . '"></span><input type="hidden" name="outcome" id="outcome' . $rnd1 . '">';
    $combo_indicator->HTML = $combo_indicator->MatchText = '<span id="indicator-container' . $rnd1 . '"></span><input type="hidden" name="indicator" id="indicator' . $rnd1 . '">';
    $combo_beneficiary_group->HTML = $combo_beneficiary_group->MatchText = '<span id="beneficiary_group-container' . $rnd1 . '"></span><input type="hidden" name="beneficiary_group" id="beneficiary_group' . $rnd1 . '">';
    $combo_beneficiary_group_relevance->Render();
    $combo_reliability->Render();
    $combo_intentionality->Render();
    $combo_equivalence->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_report__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['report'] : $filterer_report);
    ?>
"};
		var current_outcome__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome'] : $filterer_outcome);
    ?>
"};
		var current_indicator__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['indicator'] : $filterer_indicator);
    ?>
"};
		var current_beneficiary_group__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['beneficiary_group'] : $filterer_beneficiary_group);
    ?>
"};
		
		jQuery(function() {
			report_reload__RAND__();
			outcome_reload__RAND__();
			<?php 
    echo !$AllowUpdate || $dvprint ? 'indicator_reload__RAND__(current_outcome__RAND__.value);' : '';
    ?>
			beneficiary_group_reload__RAND__();
		});
		function report_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#report-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="report"]').val(resp.results[0].id);


						if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'report' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_report__RAND__.value = e.added.id;
				current_report__RAND__.text = e.added.text;
				jQuery('[name="report"]').val(e.added.id);


				if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
			}).done(function(resp){
				jQuery('#report-container__RAND__').html('<span id="report-match-text">' + resp.results[0].text + '</span>');

				if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function outcome_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#outcome-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome"]').val(resp.results[0].id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

						if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'outcome' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome__RAND__.value = e.added.id;
				current_outcome__RAND__.text = e.added.text;
				jQuery('[name="outcome"]').val(e.added.id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

				if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
			}).done(function(resp){
				jQuery('#outcome-container__RAND__').html('<span id="outcome-match-text">' + resp.results[0].text + '</span>');

				if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function indicator_reload__RAND__(filterer_outcome){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#indicator-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_outcome: filterer_outcome, id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="indicator"]').val(resp.results[0].id);


						if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_outcome: filterer_outcome, s: term, p: page, t: 'entries', f: 'indicator' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_indicator__RAND__.value = e.added.id;
				current_indicator__RAND__.text = e.added.text;
				jQuery('[name="indicator"]').val(e.added.id);


				if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
			}).done(function(resp){
				jQuery('#indicator-container__RAND__').html('<span id="indicator-match-text">' + resp.results[0].text + '</span>');

				if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
		function beneficiary_group_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#beneficiary_group-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="beneficiary_group"]').val(resp.results[0].id);


						if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'beneficiary_group' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_beneficiary_group__RAND__.value = e.added.id;
				current_beneficiary_group__RAND__.text = e.added.text;
				jQuery('[name="beneficiary_group"]').val(e.added.id);


				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
			}).done(function(resp){
				jQuery('#beneficiary_group-container__RAND__').html('<span id="beneficiary_group-match-text">' + resp.results[0].text + '</span>');

				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/entries_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/entries_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Entry details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#report').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#report_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#outcome').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#indicator').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#indicator_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#score').replaceWith('<p class=\"form-control-static\" id=\"score\">' + (jQuery('#score').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_relevance').replaceWith('<p class=\"form-control-static\" id=\"beneficiary_group_relevance\">' + (jQuery('#beneficiary_group_relevance').val() || '') + '</p>'); jQuery('#beneficiary_group_relevance-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#comment').replaceWith('<p class=\"form-control-static\" id=\"comment\">' + (jQuery('#comment').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reference').replaceWith('<p class=\"form-control-static\" id=\"reference\">' + (jQuery('#reference').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reliability').replaceWith('<p class=\"form-control-static\" id=\"reliability\">' + (jQuery('#reliability').val() || '') + '</p>'); jQuery('#reliability-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#intentionality').replaceWith('<p class=\"form-control-static\" id=\"intentionality\">' + (jQuery('#intentionality').val() || '') + '</p>'); jQuery('#intentionality-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#equivalence').replaceWith('<p class=\"form-control-static\" id=\"equivalence\">' + (jQuery('#equivalence').val() || '') + '</p>'); jQuery('#equivalence-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(created)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_created->GetHTML(true) . '</p>' : $combo_created->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(created)%%>', $combo_created->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(report)%%>', $combo_report->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(report)%%>', $combo_report->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(report)%%>', urlencode($combo_report->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(outcome)%%>', $combo_outcome->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome)%%>', $combo_outcome->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome)%%>', urlencode($combo_outcome->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(indicator)%%>', $combo_indicator->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(indicator)%%>', $combo_indicator->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(indicator)%%>', urlencode($combo_indicator->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group)%%>', $combo_beneficiary_group->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group)%%>', $combo_beneficiary_group->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(beneficiary_group)%%>', urlencode($combo_beneficiary_group->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(reliability)%%>', $combo_reliability->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(reliability)%%>', $combo_reliability->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(intentionality)%%>', $combo_intentionality->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(intentionality)%%>', $combo_intentionality->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(equivalence)%%>', $combo_equivalence->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(equivalence)%%>', $combo_equivalence->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(report)%%>', $combo_report->SelectedData ? "<span id=\"reports_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"reports_view.php?SelectedID=" . urlencode($combo_report->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(outcome)%%>', $combo_outcome->SelectedData ? "<span id=\"outcomes_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcomes_view.php?SelectedID=" . urlencode($combo_outcome->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(indicator)%%>', $combo_indicator->SelectedData ? "<span id=\"indicators_plink3\" class=\"hidden\"><a class=\"btn btn-default\" href=\"indicators_view.php?SelectedID=" . urlencode($combo_indicator->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(beneficiary_group)%%>', $combo_beneficiary_group->SelectedData ? "<span id=\"beneficiary_groups_plink4\" class=\"hidden\"><a class=\"btn btn-default\" href=\"beneficiary_groups_view.php?SelectedID=" . urlencode($combo_beneficiary_group->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(entry_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created_by)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(report)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(indicator)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(score)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group_relevance)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(comment)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reference)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reliability)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(intentionality)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(equivalence)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', htmlspecialchars($row['entry_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode($urow['entry_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', @date('d/m/Y', @strtotime(htmlspecialchars($row['created'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode(@date('d/m/Y', @strtotime(htmlspecialchars($urow['created'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', htmlspecialchars($row['created_by'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode($urow['created_by']), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', htmlspecialchars($row['report'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode($urow['report']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', htmlspecialchars($row['outcome'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode($urow['outcome']), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', htmlspecialchars($row['indicator'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode($urow['indicator']), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', htmlspecialchars($row['score'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode($urow['score']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', htmlspecialchars($row['beneficiary_group'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode($urow['beneficiary_group']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', htmlspecialchars($row['beneficiary_group_relevance'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode($urow['beneficiary_group_relevance']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(comment)%%>', nl2br(htmlspecialchars($row['comment'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(comment)%%>', htmlspecialchars($row['comment'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode($urow['comment']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', htmlspecialchars($row['reference'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode($urow['reference']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', htmlspecialchars($row['reliability'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode($urow['reliability']), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', htmlspecialchars($row['intentionality'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode($urow['intentionality']), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', htmlspecialchars($row['equivalence'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode($urow['equivalence']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode('<%%creationDate%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', '<%%creatorUsername%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(comment)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "\toutcome_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id='+encodeURIComponent('" . addslashes($row['outcome']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id=' + encodeURIComponent(current_outcome{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('outcome{$rnd1}').disable(); \$('outcomeLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('outcome{$rnd1}').enable(); " : "\$('outcome{$rnd1}').disable(); ") . "\$('outcomeLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('outcome_caption') != undefined) \$('outcome_caption').onchange=outcome_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: entries_dv
    if (function_exists('entries_dv')) {
        $args = array();
        entries_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
<?php

global $SETTINGS;
require_once "lib/menus/database/listTables_functions.php";
$tableList = getTableList();
?>

<form method="post" action="?" autocomplete="off">
<input type="hidden" name="menu" id="menu" value="database" />
<input type="hidden" name="_defaultAction" value='' />
<?php 
echo security_getHiddenCsrfTokenField();
?>

<div class="content-box">

  <div class="content-box-header">
    <h3>
      <?php 
et('Admin');
?>
 &gt;
      <a href="?menu=database&amp;action=listTables"><?php 
echo t('Section Editors');
?>
</a>
    </h3>

    <div class="clear"></div>
  </div> <!-- End .content-box-header -->
Esempio n. 18
0
function outcome_areas_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('outcome_areas');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='outcome_areas' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='outcome_areas' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `outcome_areas` where `outcome_area_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
    } else {
    }
    ob_start();
    ?>

	<script>
		// initial lookup values
		
		jQuery(function() {
		});
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/outcome_areas_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/outcome_areas_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Outcome area details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return outcome_areas_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return outcome_areas_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return outcome_areas_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#name').replaceWith('<p class=\"form-control-static\" id=\"name\">' + (jQuery('#name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $noUploads = true;
    }
    // process combos
    // process foreign key links
    if ($selected_id) {
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(outcome_area_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(outcome_area_id)%%>', htmlspecialchars($row['outcome_area_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area_id)%%>', urlencode($urow['outcome_area_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', htmlspecialchars($row['name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode($urow['name']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(description)%%>', nl2br(htmlspecialchars($row['description'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(outcome_area_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: outcome_areas_dv
    if (function_exists('outcome_areas_dv')) {
        $args = array();
        outcome_areas_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 19
0
function NavMenus($options = array())
{
    if (!defined('PREPEND_PATH')) {
        define('PREPEND_PATH', '');
    }
    global $Translation;
    $menu = array();
    $prepend_path = PREPEND_PATH;
    /* default options */
    if (empty($options)) {
        $options = array('tabs' => 7);
    }
    $table_group_name = array_keys(get_table_groups());
    /* 0 => group1, 1 => group2 .. */
    /* if only one group named 'None', set to translation of 'select a table' */
    if (count($table_group_name) == 1 && $table_group_name[0] == 'None') {
        $table_group_name[0] = $Translation['select a table'];
    }
    $table_group_index = array_flip($table_group_name);
    /* group1 => 0, group2 => 1 .. */
    $t = time();
    $arrTables = getTableList();
    if (is_array($arrTables)) {
        foreach ($arrTables as $tn => $tc) {
            /* ---- list of tables where hide link in nav menu is set ---- */
            $tChkHL = array_search($tn, array());
            if ($tChkHL !== false && $tChkHL !== null) {
                continue;
            }
            /* ---- list of tables where filter first is set ---- */
            $tChkFF = array_search($tn, array('submitlog', 'paddata'));
            if ($tChkFF !== false && $tChkFF !== null) {
                $searchFirst = '&Filter_x=1';
            } else {
                $searchFirst = '';
            }
            /* when no groups defined, $table_group_index['None'] is NULL, so $menu_index is still set to 0 */
            $menu_index = intval($table_group_index[$tc[3]]);
            $menu[$menu_index] .= "<li><a href=\"{$prepend_path}{$tn}_view.php?t={$t}{$searchFirst}\"><img src=\"{$prepend_path}" . ($tc[2] ? $tc[2] : 'blank.gif') . "\" height=\"32\"> {$tc[0]}</a></li>";
        }
    }
    // custom nav links, as defined in "hooks/links-navmenu.php"
    global $navLinks;
    if (is_array($navLinks)) {
        $memberInfo = getMemberInfo();
        $links_added = array();
        foreach ($navLinks as $link) {
            if (!isset($link['url']) || !isset($link['title'])) {
                continue;
            }
            if ($memberInfo['admin'] || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
                $menu_index = intval($link['table_group']);
                if (!$links_added[$menu_index]) {
                    $menu[$menu_index] .= '<li class="divider"></li>';
                }
                /* add prepend_path to custom links if they aren't absolute links */
                if (!preg_match('/^(http|\\/\\/)/i', $link['url'])) {
                    $link['url'] = $prepend_path . $link['url'];
                }
                if (!preg_match('/^(http|\\/\\/)/i', $link['icon']) && $link['icon']) {
                    $link['icon'] = $prepend_path . $link['icon'];
                }
                $menu[$menu_index] .= "<li><a href=\"{$link['url']}\"><img src=\"" . ($link['icon'] ? $link['icon'] : "{$prepend_path}blank.gif") . "\" height=\"32\"> {$link['title']}</a></li>";
                $links_added[$menu_index]++;
            }
        }
    }
    $menu_wrapper = '';
    for ($i = 0; $i < count($menu); $i++) {
        $menu_wrapper .= <<<EOT
\t\t\t\t<li class="dropdown">
\t\t\t\t\t<a href="#" class="dropdown-toggle" data-toggle="dropdown">{$table_group_name[$i]} <b class="caret"></b></a>
\t\t\t\t\t<ul class="dropdown-menu" role="menu">{$menu[$i]}</ul>
\t\t\t\t</li>
EOT;
    }
    return $menu_wrapper;
}
Esempio n. 20
0
function outcomes_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('outcomes');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_outcome_area = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome_area']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: outcome_area
    $combo_outcome_area = new DataCombo();
    // combobox: strata
    $combo_strata = new Combo();
    $combo_strata->ListType = 0;
    $combo_strata->MultipleSeparator = ', ';
    $combo_strata->ListBoxHeight = 10;
    $combo_strata->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')) {
        $strata_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')));
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($strata_data)));
        $combo_strata->ListData = $combo_strata->ListItem;
    } else {
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Individuals;;Community, Sector & Society")));
        $combo_strata->ListData = $combo_strata->ListItem;
    }
    $combo_strata->SelectName = 'strata';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='outcomes' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='outcomes' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `outcomes` where `outcome_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_outcome_area->SelectedData = $row['outcome_area'];
        $combo_strata->SelectedData = $row['strata'];
    } else {
        $combo_outcome_area->SelectedData = $filterer_outcome_area;
        $combo_strata->SelectedText = $_REQUEST['FilterField'][1] == '4' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_outcome_area->HTML = $combo_outcome_area->MatchText = '<span id="outcome_area-container' . $rnd1 . '"></span><input type="hidden" name="outcome_area" id="outcome_area' . $rnd1 . '">';
    $combo_strata->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_outcome_area__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome_area'] : $filterer_outcome_area);
    ?>
"};
		
		jQuery(function() {
			outcome_area_reload__RAND__();
		});
		function outcome_area_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#outcome_area-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome_area"]').val(resp.results[0].id);


						if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'outcomes', f: 'outcome_area' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome_area__RAND__.value = e.added.id;
				current_outcome_area__RAND__.text = e.added.text;
				jQuery('[name="outcome_area"]').val(e.added.id);


				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
			}).done(function(resp){
				jQuery('#outcome_area-container__RAND__').html('<span id="outcome_area-match-text">' + resp.results[0].text + '</span>');

				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
			});
		<?php 
    }
    ?>

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/outcomes_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/outcomes_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Outcome details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#outcome_area').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_area_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#strata').replaceWith('<p class=\"form-control-static\" id=\"strata\">' + (jQuery('#strata').val() || '') + '</p>'); jQuery('#strata-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(outcome_area)%%>', $combo_outcome_area->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome_area)%%>', $combo_outcome_area->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome_area)%%>', urlencode($combo_outcome_area->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(strata)%%>', $combo_strata->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(strata)%%>', $combo_strata->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(outcome_area)%%>', $combo_outcome_area->SelectedData ? "<span id=\"outcome_areas_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcome_areas_view.php?SelectedID=" . urlencode($combo_outcome_area->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(outcome_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome_area)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(strata)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', htmlspecialchars($row['outcome_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode($urow['outcome_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', htmlspecialchars($row['outcome_area'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode($urow['outcome_area']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(description)%%>', nl2br(htmlspecialchars($row['description'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', htmlspecialchars($row['strata'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode($urow['strata']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: outcomes_dv
    if (function_exists('outcomes_dv')) {
        $args = array();
        outcomes_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 21
0
<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);
$currDir = dirname(__FILE__);
include "{$currDir}/defaultLang.php";
include "{$currDir}/language.php";
include "{$currDir}/lib.php";
$x = new DataList();
$x->TableTitle = $Translation['homepage'];
$tablesPerRow = 2;
$arrTables = getTableList();
// according to provided GET parameters, either log out, show login form (possibly with a failed login message), or show homepage
if ($_GET['signOut'] == 1) {
    logOutMember();
} elseif ($_GET['loginFailed'] == 1 || $_GET['signIn'] == 1) {
    include "{$currDir}/login.php";
} else {
    include "{$currDir}/home.php";
}
Esempio n. 22
0
 /**
  * CSVファイルを書きだす
  *
  * @param string $configKeyName
  * @param string $path
  * @return boolean
  */
 function _writeCsv($plugin, $path, $exclude = array())
 {
     $pluginTables = array();
     if ($plugin != 'core') {
         $pluginPath = BcUtil::getSchemaPath($plugin);
         $Folder = new Folder($pluginPath);
         $files = $Folder->read(true, true, false);
         $pluginTables = $files[1];
         foreach ($pluginTables as $key => $pluginTable) {
             if (preg_match('/^(.+)\\.php$/', $pluginTable, $matches)) {
                 $pluginTables[$key] = $matches[1];
             } else {
                 unset($pluginTables[$key]);
             }
         }
     }
     $pluginKey = Inflector::underscore($plugin);
     $db = ConnectionManager::getDataSource('default');
     $db->cacheSources = false;
     $tables = $db->listSources();
     $tableList = getTableList();
     $result = true;
     foreach ($tables as $table) {
         if ($plugin == 'core' && in_array($table, $tableList['core']) || $plugin != 'core' && in_array($table, $tableList['plugin'])) {
             $table = str_replace($db->config['prefix'], '', $table);
             if (in_array($table, $exclude)) {
                 continue;
             }
             if ($pluginKey != 'core' && !in_array($table, $pluginTables)) {
                 continue;
             }
             if (!$db->writeCsv(array('path' => $path . $table . '.csv', 'encoding' => 'SJIS', 'init' => false, 'plugin' => $plugin == 'core' ? null : $plugin))) {
                 $result = false;
             }
         }
     }
     return $result;
 }
    // hook: member_activity
    if (function_exists('member_activity')) {
        $args = array();
        member_activity($mi, 'password', $args);
    }
    exit;
}
/* get profile info */
/* 
	$mi already contains the profile info, as documented at: 
	http://bigprof.com/appgini/help/working-with-generated-web-database-application/hooks/memberInfo

	custom field names are stored in $adminConfig['custom1'] to $adminConfig['custom4']
*/
$permissions = array();
$userTables = getTableList();
if (is_array($userTables)) {
    foreach ($userTables as $tn => $tc) {
        $permissions[$tn] = getTablePermissions($tn);
    }
}
/* the profile page view */
include_once "{$currDir}/header.php";
?>

	<div class="page-header">
		<h1><?php 
echo sprintf($Translation['Hello user'], $mi['username']);
?>
</h1>
	</div>
<?php

$currDir = dirname(__FILE__);
require "{$currDir}/incCommon.php";
include "{$currDir}/incHeader.php";
/* application schema as created in AppGini */
$schema = array('customers' => array('CustomerID' => array('appgini' => 'VARCHAR(5) not null primary key '), 'CompanyName' => array('appgini' => 'VARCHAR(40) '), 'ContactName' => array('appgini' => 'VARCHAR(30) '), 'ContactTitle' => array('appgini' => 'VARCHAR(30) '), 'Address' => array('appgini' => 'VARCHAR(60) '), 'City' => array('appgini' => 'VARCHAR(15) '), 'Region' => array('appgini' => 'VARCHAR(15) '), 'PostalCode' => array('appgini' => 'VARCHAR(10) '), 'Country' => array('appgini' => 'VARCHAR(15) '), 'Phone' => array('appgini' => 'VARCHAR(24) '), 'Fax' => array('appgini' => 'VARCHAR(24) ')), 'employees' => array('EmployeeID' => array('appgini' => 'INT not null primary key auto_increment '), 'TitleOfCourtesy' => array('appgini' => 'VARCHAR(50) '), 'Photo' => array('appgini' => 'VARCHAR(40) '), 'LastName' => array('appgini' => 'VARCHAR(50) '), 'FirstName' => array('appgini' => 'VARCHAR(10) '), 'Title' => array('appgini' => 'VARCHAR(30) '), 'BirthDate' => array('appgini' => 'DATE '), 'HireDate' => array('appgini' => 'DATE '), 'Address' => array('appgini' => 'VARCHAR(50) '), 'City' => array('appgini' => 'VARCHAR(15) '), 'Region' => array('appgini' => 'VARCHAR(15) '), 'PostalCode' => array('appgini' => 'VARCHAR(10) '), 'Country' => array('appgini' => 'VARCHAR(15) '), 'HomePhone' => array('appgini' => 'VARCHAR(24) '), 'Extension' => array('appgini' => 'VARCHAR(4) '), 'Notes' => array('appgini' => 'TEXT '), 'ReportsTo' => array('appgini' => 'INT ')), 'orders' => array('OrderID' => array('appgini' => 'INT not null primary key auto_increment '), 'CustomerID' => array('appgini' => 'VARCHAR(5) '), 'EmployeeID' => array('appgini' => 'INT '), 'OrderDate' => array('appgini' => 'DATE '), 'RequiredDate' => array('appgini' => 'DATE '), 'ShippedDate' => array('appgini' => 'DATE '), 'ShipVia' => array('appgini' => 'INT(11) '), 'Freight' => array('appgini' => 'FLOAT(10,2) default \'0\' '), 'ShipName' => array('appgini' => 'VARCHAR(5) '), 'ShipAddress' => array('appgini' => 'VARCHAR(5) '), 'ShipCity' => array('appgini' => 'VARCHAR(5) '), 'ShipRegion' => array('appgini' => 'VARCHAR(5) '), 'ShipPostalCode' => array('appgini' => 'VARCHAR(5) '), 'ShipCountry' => array('appgini' => 'VARCHAR(5) ')), 'order_details' => array('odID' => array('appgini' => 'INT unsigned not null primary key auto_increment '), 'OrderID' => array('appgini' => 'INT default \'0\' '), 'ProductID' => array('appgini' => 'INT default \'0\' '), 'Category' => array('appgini' => 'INT '), 'UnitPrice' => array('appgini' => 'FLOAT(10,2) default \'0\' '), 'Quantity' => array('appgini' => 'SMALLINT default \'1\' '), 'Discount' => array('appgini' => 'FLOAT(10,2) default \'0\' ')), 'products' => array('ProductID' => array('appgini' => 'INT not null primary key auto_increment '), 'ProductName' => array('appgini' => 'VARCHAR(50) '), 'SupplierID' => array('appgini' => 'INT(11) '), 'CategoryID' => array('appgini' => 'INT '), 'QuantityPerUnit' => array('appgini' => 'VARCHAR(50) '), 'UnitPrice' => array('appgini' => 'FLOAT(10,2) default \'0\' '), 'UnitsInStock' => array('appgini' => 'SMALLINT default \'0\' '), 'UnitsOnOrder' => array('appgini' => 'SMALLINT(6) default \'0\' '), 'ReorderLevel' => array('appgini' => 'SMALLINT default \'0\' '), 'Discontinued' => array('appgini' => 'TINYINT default \'0\' ')), 'categories' => array('CategoryID' => array('appgini' => 'INT not null primary key auto_increment '), 'Picture' => array('appgini' => 'VARCHAR(40) '), 'CategoryName' => array('appgini' => 'VARCHAR(50) unique '), 'Description' => array('appgini' => 'TEXT ')), 'suppliers' => array('SupplierID' => array('appgini' => 'INT(11) not null primary key auto_increment '), 'CompanyName' => array('appgini' => 'VARCHAR(50) '), 'ContactName' => array('appgini' => 'VARCHAR(30) '), 'ContactTitle' => array('appgini' => 'VARCHAR(30) '), 'Address' => array('appgini' => 'VARCHAR(50) '), 'City' => array('appgini' => 'VARCHAR(15) '), 'Region' => array('appgini' => 'VARCHAR(15) '), 'PostalCode' => array('appgini' => 'VARCHAR(10) '), 'Country' => array('appgini' => 'VARCHAR(50) '), 'Phone' => array('appgini' => 'VARCHAR(24) '), 'Fax' => array('appgini' => 'VARCHAR(24) '), 'HomePage' => array('appgini' => 'TEXT ')), 'shippers' => array('ShipperID' => array('appgini' => 'INT(11) not null primary key auto_increment '), 'CompanyName' => array('appgini' => 'VARCHAR(40) not null '), 'Phone' => array('appgini' => 'VARCHAR(24) ')));
$table_captions = getTableList();
/* function for preparing field definition for comparison */
function prepare_def($def)
{
    $def = trim($def);
    $def = strtolower($def);
    /* ignore length for int data types */
    $def = preg_replace('/int\\w*\\([0-9]+\\)/', 'int', $def);
    /* make sure there is always a space before mysql words */
    $def = preg_replace('/(\\S)(unsigned|not null|binary|zerofill|auto_increment|default)/', '$1 $2', $def);
    /* treat 0.000.. same as 0 */
    $def = preg_replace('/([0-9])*\\.0+/', '$1', $def);
    /* treat unsigned zerofill same as zerofill */
    $def = str_ireplace('unsigned zerofill', 'zerofill', $def);
    /* ignore zero-padding for date data types */
    $def = preg_replace("/date\\s*default\\s*'([0-9]{4})-0?([1-9])-0?([1-9])'/i", "date default '\$1-\$2-\$3'", $def);
    return $def;
}
/* process requested fixes */
$fix_table = isset($_GET['t']) ? $_GET['t'] : false;
$fix_field = isset($_GET['f']) ? $_GET['f'] : false;
if ($fix_table && $fix_field && isset($schema[$fix_table][$fix_field])) {
    $field_added = $field_updated = false;
    // field exists?
Esempio n. 25
0
function categories_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('categories');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='categories' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='categories' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `categories` where `CategoryID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
    } else {
    }
    ob_start();
    ?>

	<script>
		// initial lookup values

		jQuery(function() {
		});
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/categories_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/categories_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Add/Edit Product Categories', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return categories_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return categories_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return categories_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#Picture').replaceWith('<div class=\"form-control-static\" id=\"Picture\">' + (jQuery('#Picture').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#CategoryName').replaceWith('<div class=\"form-control-static\" id=\"CategoryName\">' + (jQuery('#CategoryName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array();
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(CategoryID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Picture)%%>', $noUploads ? '' : '<input type=hidden name=MAX_FILE_SIZE value=204800>' . $Translation['upload image'] . ' <input type="file" name="Picture" id="Picture">', $templateCode);
    if ($AllowUpdate && $row['Picture'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(Picture)%%>', '<br><input type="checkbox" name="Picture_remove" id="Picture_remove" value="1"> <label for="Picture_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(Picture)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(CategoryName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Description)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(CategoryID)%%>', htmlspecialchars($row['CategoryID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CategoryID)%%>', urlencode($urow['CategoryID']), $templateCode);
        $row['Picture'] = $row['Picture'] != '' ? $row['Picture'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(Picture)%%>', htmlspecialchars($row['Picture'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Picture)%%>', urlencode($urow['Picture']), $templateCode);
        $templateCode = str_replace('<%%VALUE(CategoryName)%%>', htmlspecialchars($row['CategoryName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CategoryName)%%>', urlencode($urow['CategoryName']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(Description)%%>', '<textarea name="Description" id="Description" rows="5">' . htmlspecialchars($row['Description'], ENT_QUOTES, 'iso-8859-1') . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(Description)%%>', $row['Description'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(Description)%%>', nl2br($row['Description']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Description)%%>', urlencode($urow['Description']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(CategoryID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CategoryID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Picture)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(CategoryName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CategoryName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(Description)%%>', '<textarea name="Description" id="Description" rows="5"></textarea>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: categories_dv
    if (function_exists('categories_dv')) {
        $args = array();
        categories_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Esempio n. 26
0
<?php

$server_name = $_POST["server_name"];
$server_port = $_POST["server_port"];
$username = $_POST["username"];
$password = $_POST["password"];
$db_name = $_POST["db_name"];
include "mysqlUtil.php";
include "mongoUtil.php";
setMysqlAuth($server_name, $server_port, $username, $password);
$tables = getTableList($db_name);
$commentedTables = get_comment_table($server_name, $server_port, $db_name);
foreach ($tables as $table) {
    if (in_array($table, $commentedTables)) {
        echo "<tr><td><a href='' class='table commented' name='{$table}'>{$table}</a></td></tr>";
    } else {
        echo "<tr><td><a href='' class='table' name='{$table}'>{$table}</a></td></tr>";
    }
}
Esempio n. 27
0
function setupMembership()
{
    // run once per request
    static $executed = false;
    if ($executed) {
        return;
    }
    $executed = true;
    $adminConfig = config('adminConfig');
    $today = @date('Y-m-d');
    $membership_tables = array('membership_groups' => "CREATE TABLE IF NOT EXISTS membership_groups (groupID int unsigned NOT NULL auto_increment, name varchar(20), description text, allowSignup tinyint, needsApproval tinyint, PRIMARY KEY (groupID)) CHARSET " . mysql_charset, 'membership_users' => "CREATE TABLE IF NOT EXISTS membership_users (memberID varchar(20) NOT NULL, passMD5 varchar(40), email varchar(100), signupDate date, groupID int unsigned, isBanned tinyint, isApproved tinyint, custom1 text, custom2 text, custom3 text, custom4 text, comments text, PRIMARY KEY (memberID)) CHARSET " . mysql_charset, 'membership_grouppermissions' => "CREATE TABLE IF NOT EXISTS membership_grouppermissions (permissionID int unsigned NOT NULL auto_increment,  groupID int, tableName varchar(100), allowInsert tinyint, allowView tinyint NOT NULL DEFAULT '0', allowEdit tinyint NOT NULL DEFAULT '0', allowDelete tinyint NOT NULL DEFAULT '0', PRIMARY KEY (permissionID)) CHARSET " . mysql_charset, 'membership_userrecords' => "CREATE TABLE IF NOT EXISTS membership_userrecords (recID bigint unsigned NOT NULL auto_increment, tableName varchar(100), pkValue varchar(255), memberID varchar(20), dateAdded bigint unsigned, dateUpdated bigint unsigned, groupID int, PRIMARY KEY (recID)) CHARSET " . mysql_charset, 'membership_userpermissions' => "CREATE TABLE IF NOT EXISTS membership_userpermissions (permissionID int unsigned NOT NULL auto_increment,  memberID varchar(20) NOT NULL, tableName varchar(100), allowInsert tinyint, allowView tinyint NOT NULL DEFAULT '0', allowEdit tinyint NOT NULL DEFAULT '0', allowDelete tinyint NOT NULL DEFAULT '0', PRIMARY KEY (permissionID)) CHARSET " . mysql_charset);
    // get db tables
    $tables = array();
    $res = sql("show tables", $eo);
    while ($row = db_fetch_array($res)) {
        $tables[] = $row[0];
    }
    // check if membership tables exist or not
    foreach ($membership_tables as $tn => $tdef) {
        if (!in_array($tn, $tables)) {
            sql($tdef, $eo);
        }
    }
    // check membership_users definition
    $membership_users = array();
    $res = sql("show columns from membership_users", $eo);
    while ($row = db_fetch_assoc($res)) {
        $membership_users[$row['Field']] = $row;
    }
    if (!in_array('pass_reset_key', array_keys($membership_users))) {
        @db_query("ALTER TABLE membership_users ADD COLUMN pass_reset_key VARCHAR(100)");
    }
    if (!in_array('pass_reset_expiry', array_keys($membership_users))) {
        @db_query("ALTER TABLE membership_users ADD COLUMN pass_reset_expiry INT UNSIGNED");
    }
    if (!$membership_users['groupID']['Key']) {
        @db_query("ALTER TABLE membership_users ADD INDEX groupID (groupID)");
    }
    // create membership indices if not existing
    $membership_userrecords = array();
    $res = sql("show keys from membership_userrecords", $eo);
    while ($row = db_fetch_assoc($res)) {
        $membership_userrecords[$row['Key_name']][$row['Seq_in_index']] = $row;
    }
    if (!$membership_userrecords['pkValue'][1]) {
        @db_query("ALTER TABLE membership_userrecords ADD INDEX pkValue (pkValue)");
    }
    if (!$membership_userrecords['tableName'][1]) {
        @db_query("ALTER TABLE membership_userrecords ADD INDEX tableName (tableName)");
    }
    if (!$membership_userrecords['memberID'][1]) {
        @db_query("ALTER TABLE membership_userrecords ADD INDEX memberID (memberID)");
    }
    if (!$membership_userrecords['groupID'][1]) {
        @db_query("ALTER TABLE membership_userrecords ADD INDEX groupID (groupID)");
    }
    if (!$membership_userrecords['tableName_pkValue'][1] || !$membership_userrecords['tableName_pkValue'][2]) {
        @db_query("ALTER IGNORE TABLE membership_userrecords ADD UNIQUE INDEX tableName_pkValue (tableName, pkValue)");
    }
    // retreive anonymous and admin groups and their permissions
    $anon_group = $adminConfig['anonymousGroup'];
    $anon_user = strtolower($adminConfig['anonymousMember']);
    $admin_group = 'Admins';
    $admin_user = strtolower($adminConfig['adminUsername']);
    $groups_permissions = array();
    $res = sql("select g.groupID, g.name, gp.tableName, gp.allowInsert, gp.allowView, gp.allowEdit, gp.allowDelete " . "from membership_groups g left join membership_grouppermissions gp on g.groupID=gp.groupID " . "where g.name='" . makeSafe($admin_group) . "' or g.name='" . makeSafe($anon_group) . "' " . "order by g.groupID, gp.tableName", $eo);
    while ($row = db_fetch_assoc($res)) {
        $groups_permissions[] = $row;
    }
    // check anonymous group and user and create if necessary
    $anon_group_id = false;
    foreach ($groups_permissions as $group) {
        if ($group['name'] == $anon_group) {
            $anon_group_id = $group['groupID'];
            break;
        }
    }
    if (!$anon_group_id) {
        sql("insert into membership_groups set name='" . makeSafe($anon_group) . "', allowSignup=0, needsApproval=0, description='Anonymous group created automatically on " . @date("Y-m-d") . "'", $eo);
        $anon_group_id = db_insert_id();
    }
    if ($anon_group_id) {
        $anon_user_db = sqlValue("select lcase(memberID) from membership_users where lcase(memberID)='" . makeSafe($anon_user) . "' and groupID='{$anon_group_id}'");
        if (!$anon_user_db || $anon_user_db != $anon_user) {
            sql("delete from membership_users where groupID='{$anon_group_id}'", $eo);
            sql("insert into membership_users set memberID='" . makeSafe($anon_user) . "', signUpDate='{$today}', groupID='{$anon_group_id}', isBanned=0, isApproved=1, comments='Anonymous member created automatically on {$today}'", $eo);
        }
    }
    // check admin group and user and create if necessary
    $admin_group_id = false;
    foreach ($groups_permissions as $group) {
        if ($group['name'] == $admin_group) {
            $admin_group_id = $group['groupID'];
            break;
        }
    }
    if (!$admin_group_id) {
        sql("insert into membership_groups set name='" . makeSafe($admin_group) . "', allowSignup=0, needsApproval=1, description='Admin group created automatically on {$today}'", $eo);
        $admin_group_id = db_insert_id();
    }
    if ($admin_group_id) {
        // check that admins can access all tables
        $all_tables = getTableList(true);
        $tables_ok = $perms_ok = array();
        foreach ($all_tables as $tn => $tc) {
            $tables_ok[$tn] = $perms_ok[$tn] = false;
        }
        foreach ($groups_permissions as $group) {
            if ($group['name'] == $admin_group) {
                if (isset($tables_ok[$group['tableName']])) {
                    $tables_ok[$group['tableName']] = true;
                    if ($group['allowInsert'] == 1 && $group['allowDelete'] == 3 && $group['allowEdit'] == 3 && $group['allowView'] == 3) {
                        $perms_ok[$group['tableName']] = true;
                    }
                }
            }
        }
        // if any table has no record in Admins permissions, create one for it
        $grant_sql = array();
        foreach ($tables_ok as $tn => $status) {
            if (!$status) {
                $grant_sql[] = "({$admin_group_id}, '{$tn}')";
            }
        }
        if (count($grant_sql)) {
            sql("insert into membership_grouppermissions (groupID, tableName) values " . implode(',', $grant_sql), $eo);
        }
        // check admin permissions and update if necessary
        $perms_sql = array();
        foreach ($perms_ok as $tn => $status) {
            if (!$status) {
                $perms_sql[] = "'{$tn}'";
            }
        }
        if (count($perms_sql)) {
            sql("update membership_grouppermissions set allowInsert=1, allowView=3, allowEdit=3, allowDelete=3 where groupID={$admin_group_id} and tableName in (" . implode(',', $perms_sql) . ")", $eo);
        }
        // check if super admin is stored in the users table and add him if not
        $admin_user_exists = sqlValue("select count(1) from membership_users where lcase(memberID)='" . makeSafe($admin_user) . "' and groupID='{$admin_group_id}'");
        if (!$admin_user_exists) {
            sql("insert into membership_users set memberID='" . makeSafe($admin_user) . "', passMD5='{$adminConfig['adminPassword']}', email='{$adminConfig['senderEmail']}', signUpDate='{$today}', groupID='{$admin_group_id}', isBanned=0, isApproved=1, comments='Admin member created automatically on {$today}'", $eo);
        }
    }
}
Esempio n. 28
0
function resetAccessData()
{
    handlePower('恢复模板数据');
    //管理权限处理
    $GLOBALS['conn='] = OpenConn();
    $splStr = '';
    $i = '';
    $s = '';
    $columnname = '';
    $title = '';
    $nCount = '';
    $webdataDir = '';
    $webdataDir = @$_REQUEST['webdataDir'];
    if ($webdataDir != '') {
        if (checkFolder($webdataDir) == false) {
            eerr('网站数据目录不存在,恢复默认数据未成功', $webdataDir);
        }
    } else {
        $webdataDir = '/Data/WebData/';
    }
    //修改网站配置
    importTXTData(GetFText($webdataDir . '/website.txt'), 'website', '修改');
    batchImportDirTXTData($webdataDir, $GLOBALS['db_PREFIX'] . 'WebColumn' . vbCrlf() . getTableList());
    //加webcolumn是因为webcolumn必需新导入数据,因为后台文章类型要从里获得20160711
    aspEcho('提示', '恢复数据完成');
    rw('<hr><a href=\'../index.php\' target=\'_blank\'>进入首页</a> | <a href="?" target=\'_blank\'>进入后台</a>');
    writeSystemLog('', '恢复默认数据' . $GLOBALS['db_PREFIX']);
    //系统日志
}
Esempio n. 29
0
function customers_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('customers');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: Country
    $combo_Country = new Combo();
    $combo_Country->ListType = 0;
    $combo_Country->MultipleSeparator = ', ';
    $combo_Country->ListBoxHeight = 10;
    $combo_Country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/customers.Country.csv')) {
        $Country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/customers.Country.csv')));
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($Country_data)));
        $combo_Country->ListData = $combo_Country->ListItem;
    } else {
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_Country->ListData = $combo_Country->ListItem;
    }
    $combo_Country->SelectName = 'Country';
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='customers' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='customers' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `customers` where `CustomerID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_Country->SelectedData = $row['Country'];
    } else {
        $combo_Country->SelectedText = $_REQUEST['FilterField'][1] == '9' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_Country->Render();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/customers_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/customers_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return customers_validateData();"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : '', $templateCode);
    }
    // set records to read only if user can't insert new records and can't edit current record
    if ($selected_id && !$AllowUpdate || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#CustomerID').replaceWith('<div class=\"form-control-static\" id=\"CustomerID\">' + (jQuery('#CustomerID').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#CompanyName').replaceWith('<div class=\"form-control-static\" id=\"CompanyName\">' + (jQuery('#CompanyName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ContactName').replaceWith('<div class=\"form-control-static\" id=\"ContactName\">' + (jQuery('#ContactName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ContactTitle').replaceWith('<div class=\"form-control-static\" id=\"ContactTitle\">' + (jQuery('#ContactTitle').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Address').replaceWith('<div class=\"form-control-static\" id=\"Address\">' + (jQuery('#Address').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<div class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Region').replaceWith('<div class=\"form-control-static\" id=\"Region\">' + (jQuery('#Region').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#PostalCode').replaceWith('<div class=\"form-control-static\" id=\"PostalCode\">' + (jQuery('#PostalCode').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Country').replaceWith('<div class=\"form-control-static\" id=\"Country\">' + (jQuery('#Country').val() || '') + '</div>'); jQuery('#Country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#Phone').replaceWith('<div class=\"form-control-static\" id=\"Phone\">' + (jQuery('#Phone').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Fax').replaceWith('<div class=\"form-control-static\" id=\"Fax\">' + (jQuery('#Fax').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(Country)%%>', $combo_Country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(Country)%%>', $combo_Country->SelectedData, $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array();
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
        }
        // if user has insert permission to parent table of a lookup field, put an add new button
        if ($pt_perm['insert'] && !$_REQUEST['Embedded']) {
            $templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(CustomerID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(CompanyName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ContactName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ContactTitle)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Region)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(PostalCode)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Fax)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', htmlspecialchars($row['CustomerID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode($urow['CustomerID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(CompanyName)%%>', htmlspecialchars($row['CompanyName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CompanyName)%%>', urlencode($urow['CompanyName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactName)%%>', htmlspecialchars($row['ContactName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactName)%%>', urlencode($urow['ContactName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactTitle)%%>', htmlspecialchars($row['ContactTitle'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactTitle)%%>', urlencode($urow['ContactTitle']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(Address)%%>', nl2br(htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1')), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(Address)%%>', htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode($urow['Address']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', htmlspecialchars($row['Region'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode($urow['Region']), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', htmlspecialchars($row['PostalCode'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode($urow['PostalCode']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', htmlspecialchars($row['Country'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode($urow['Country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Phone)%%>', htmlspecialchars($row['Phone'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Phone)%%>', urlencode($urow['Phone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Fax)%%>', htmlspecialchars($row['Fax'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Fax)%%>', urlencode($urow['Fax']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(CompanyName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CompanyName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ContactTitle)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ContactTitle)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Phone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Fax)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Fax)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: customers_dv
    if (function_exists('customers_dv')) {
        $args = array();
        customers_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function patients_form($selected_id = "", $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('patients');
    if (!$arrPerm[1] && $selected_id == "") {
        return "";
    }
    // combobox: gender
    $combo_gender = new Combo();
    $combo_gender->ListType = 2;
    $combo_gender->MultipleSeparator = ', ';
    $combo_gender->ListBoxHeight = 10;
    $combo_gender->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/patients.gender.csv')) {
        $gender_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/patients.gender.csv')));
        $combo_gender->ListItem = explode(";;", $gender_data);
        $combo_gender->ListData = explode(";;", $gender_data);
    } else {
        $combo_gender->ListItem = explode(";;", "Male;;Female;;Other;;Unknown");
        $combo_gender->ListData = explode(";;", "Male;;Female;;Other;;Unknown");
    }
    $combo_gender->SelectName = "gender";
    $combo_gender->AllowNull = false;
    // combobox: birth_date
    $combo_birth_date = new DateCombo();
    $combo_birth_date->DateFormat = "mdy";
    $combo_birth_date->MinYear = 1900;
    $combo_birth_date->MaxYear = 2100;
    $combo_birth_date->DefaultDate = parseMySQLDate('', '');
    $combo_birth_date->MonthNames = $Translation['month names'];
    $combo_birth_date->CSSOptionClass = 'Option';
    $combo_birth_date->CSSSelectedClass = 'SelectedOption';
    $combo_birth_date->NamePrefix = 'birth_date';
    // combobox: state
    $combo_state = new Combo();
    $combo_state->ListType = 0;
    $combo_state->MultipleSeparator = ', ';
    $combo_state->ListBoxHeight = 10;
    $combo_state->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/patients.state.csv')) {
        $state_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/patients.state.csv')));
        $combo_state->ListItem = explode(";;", $state_data);
        $combo_state->ListData = explode(";;", $state_data);
    } else {
        $combo_state->ListItem = explode(";;", "AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY");
        $combo_state->ListData = explode(";;", "AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY");
    }
    $combo_state->SelectName = "state";
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='patients' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='patients' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `patients` where `id`='" . makeSafe($selected_id) . "'");
        $row = mysql_fetch_array($res);
        $combo_gender->SelectedData = $row["gender"];
        $combo_birth_date->DefaultDate = $row["birth_date"];
        $combo_state->SelectedData = $row["state"];
        $row['filed'] = sqlValue("select DATE_FORMAT(`filed`, '%c/%e/%Y %l:%i%p') from `patients` where `id`='" . makeSafe($selected_id) . "'");
        $row['last_modified'] = sqlValue("select DATE_FORMAT(`last_modified`, '%c/%e/%Y %l:%i%p') from `patients` where `id`='" . makeSafe($selected_id) . "'");
    } else {
        $combo_gender->SelectedText = $_REQUEST['FilterField'][1] == '4' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Unknown";
        $combo_state->SelectedText = $_REQUEST['FilterField'][1] == '9' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_gender->Render();
    $combo_state->Render();
    // code for template based detail view forms
    // open the detail view template
    if (($_POST['dvprint_x'] != '' || $_GET['dvprint_x'] != '') && $selected_id) {
        $templateCode = @implode('', @file('./templates/patients_templateDVP.html'));
        $dvprint = true;
    } else {
        $templateCode = @implode('', @file('./templates/patients_templateDV.html'));
        $dvprint = false;
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Patient details', $templateCode);
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<input type="image" src="insert.gif" name="insert" alt="' . $Translation['add new record'] . '" onclick="return validateData();">', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    if ($selected_id) {
        $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<input type="image" src="print.gif" vspace="1" name="dvprint" id="dvprint" alt="' . $Translation['printer friendly view'] . '" onclick="document.myform.reset(); return true;" style="margin-bottom: 20px;">', $templateCode);
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<input type="image" src="update.gif" vspace="1" name="update" alt="' . $Translation['update record'] . '" onclick="return validateData();">', $templateCode);
        } else {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
            // set records to read only if user can't insert new records
            if (!$arrPerm[1]) {
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('id').length){ document.getElementsByName('id')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('last_name').length){ document.getElementsByName('last_name')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('first_name').length){ document.getElementsByName('first_name')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('gender').length){ var gender=document.getElementsByName('gender'); for(var i=0; i<gender.length; i++){ gender[i].disabled=true; } }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('birth_date').length){ document.getElementsByName('birth_date')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('birth_dateDay').length){ var birth_dateDay=document.getElementsByName('birth_dateDay')[0]; birth_dateDay.disabled=true; birth_dateDay.style.backgroundColor='white'; birth_dateDay.style.color='black'; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('birth_dateMonth').length){ var birth_dateMonth=document.getElementsByName('birth_dateMonth')[0]; birth_dateMonth.disabled=true; birth_dateMonth.style.backgroundColor='white'; birth_dateMonth.style.color='black'; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('birth_dateYear').length){ var birth_dateYear=document.getElementsByName('birth_dateYear')[0]; birth_dateYear.disabled=true; birth_dateYear.style.backgroundColor='white'; birth_dateYear.style.color='black'; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('age').length){ document.getElementsByName('age')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('address').length){ document.getElementsByName('address')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('city').length){ document.getElementsByName('city')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('state').length){ var state=document.getElementsByName('state')[0]; state.disabled=true; state.style.backgroundColor='white'; state.style.color='black'; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('zip').length){ document.getElementsByName('zip')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('home_phone').length){ document.getElementsByName('home_phone')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('work_phone').length){ document.getElementsByName('work_phone')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('mobile').length){ document.getElementsByName('mobile')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('filed').length){ document.getElementsByName('filed')[0].readOnly=true; }\n";
                $jsReadOnly .= "\n\n\tif(document.getElementsByName('last_modified').length){ document.getElementsByName('last_modified')[0].readOnly=true; }\n";
                $noUploads = true;
            }
        }
        if ($arrPerm[4] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[4] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[4] == 3) {
            // allow delete?
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '<input type="image" src="delete.gif" vspace="1" name="delete" alt="' . $Translation['delete record'] . '" onClick="return confirm(\'' . $Translation['are you sure?'] . '\');">', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', "<input type=image src=deselect.gif vspace=1 name=deselect alt=\"" . $Translation['deselect record'] . "\" onclick=\"document.myform.reset(); return true;\">", $templateCode);
    } else {
        $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', $ShowCancel ? "<input type=image src=cancel.gif vspace=1 name=deselect alt=\"" . $Translation['deselect record'] . "\" onclick=\"document.myform.reset(); return true;\">" : '', $templateCode);
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(gender)%%>', $combo_gender->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(gender)%%>', $combo_gender->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(birth_date)%%>', $combo_birth_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(birth_date)%%>', $combo_birth_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(state)%%>', $combo_state->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(state)%%>', $combo_state->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(last_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(first_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(gender)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(birth_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(age)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(city)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(state)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(zip)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(home_phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(work_phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(mobile)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(other_details)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(comments)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(filed)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(last_modified)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(last_name)%%>', htmlspecialchars($row['last_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(first_name)%%>', htmlspecialchars($row['first_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(gender)%%>', htmlspecialchars($row['gender'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(birth_date)%%>', @date('n/j/Y', @strtotime(htmlspecialchars($row['birth_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%VALUE(age)%%>', htmlspecialchars($row['age'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', htmlspecialchars($row['address'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(city)%%>', htmlspecialchars($row['city'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(state)%%>', htmlspecialchars($row['state'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(zip)%%>', htmlspecialchars($row['zip'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(home_phone)%%>', htmlspecialchars($row['home_phone'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(work_phone)%%>', htmlspecialchars($row['work_phone'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(mobile)%%>', htmlspecialchars($row['mobile'], ENT_QUOTES), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(other_details)%%>', '<textarea name="other_details" id="other_details" cols="50" rows="5" class="TextBox">' . htmlspecialchars($row['other_details'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(other_details)%%>', $row['other_details'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(other_details)%%>', $row['other_details'], $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" cols="50" rows="5" class="TextBox">' . htmlspecialchars($row['comments'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(comments)%%>', $row['comments'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(comments)%%>', $row['comments'], $templateCode);
        $templateCode = str_replace('<%%VALUE(filed)%%>', htmlspecialchars($row['filed'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%VALUE(last_modified)%%>', htmlspecialchars($row['last_modified'], ENT_QUOTES), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(last_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(first_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(gender)%%>', 'Unknown', $templateCode);
        $templateCode = str_replace('<%%VALUE(birth_date)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(age)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(city)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(state)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(zip)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(home_phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(work_phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%VALUE(mobile)%%>', '', $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(other_details)%%>', '<textarea name="other_details" id="other_details" cols="50" rows="5" class="TextBox"></textarea>', $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" cols="50" rows="5" class="TextBox"></textarea>', $templateCode);
        $templateCode = str_replace('<%%VALUE(filed)%%>', '<%%creationDateTime%%>', $templateCode);
        $templateCode = str_replace('<%%VALUE(last_modified)%%>', '<%%editingDateTime%%>', $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!--', $templateCode);
    $templateCode = str_replace('%%>', '-->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tif(document.getElementById('" . $name . "_link')!=undefined){\n";
            $templateCode .= "\t\tdocument.getElementById('" . $name . "_link').style.visibility='visible';\n";
            $templateCode .= "\t}\n";
            for ($i = 1; $i < 10; $i++) {
                $templateCode .= "\tif(document.getElementById('" . $name . "_plink{$i}')!=undefined){\n";
                $templateCode .= "\t\tdocument.getElementById('" . $name . "_plink{$i}').style.visibility='visible';\n";
                $templateCode .= "\t}\n";
            }
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n\tfunction validateData(){";
        $templateCode .= "\n\t\tif(\$F('last_name')==''){ alert('" . addslashes($Translation['error:']) . ' "Last name": ' . addslashes($Translation['field not null']) . "'); \$('last_name').focus(); return false; }";
        $templateCode .= "\n\t\tif(\$F('first_name')==''){ alert('" . addslashes($Translation['error:']) . ' "First name": ' . addslashes($Translation['field not null']) . "'); \$('first_name').focus(); return false; }";
        $templateCode .= "\n\t\tif(\$F('gender')==''){ alert('" . addslashes($Translation['error:']) . ' "Gender": ' . addslashes($Translation['field not null']) . "'); \$('gender').focus(); return false; }";
        $templateCode .= "\n\t\treturn true;";
        $templateCode .= "\n\t}";
        $templateCode .= "\n</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "});";
    $templateCode .= "</script>";
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: patients_dv
    if (function_exists('patients_dv')) {
        $args = array();
        patients_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}