Example #1
0
/**
 * Checks if an email address is valid
 *
 * @since 1.0
 * @package facileManager
 *
 * @param string $address Email address to validate
 * @return boolean
 */
function printfmDNSUsersForm($user_module_perms, $module_name)
{
    global $__FM_CONFIG, $fmdb;
    if (!array_key_exists($module_name, $__FM_CONFIG)) {
        /** Include module variables */
        @(include dirname(__FILE__) . '/variables.inc.php');
    }
    $available_zones_perms = 0;
    if (isSerialized($user_module_perms)) {
        $user_module_perms = unserialize($user_module_perms);
    }
    $available_zones_perms = isset($user_module_perms[$module_name]['access_specific_zones']) ? $user_module_perms[$module_name]['access_specific_zones'] : 0;
    /** Get available zones */
    $available_zones[0][] = 'All Zones';
    $available_zones[0][] = '0';
    basicGetList('fm_' . $__FM_CONFIG[$module_name]['prefix'] . 'domains', 'domain_mapping`,`domain_name', 'domain_', 'AND domain_clone_domain_id=0');
    if ($fmdb->num_rows) {
        $results = $fmdb->last_result;
        for ($i = 0; $i < $fmdb->num_rows; $i++) {
            $available_zones[$i + 1][] = !function_exists('displayFriendlyDomainName') ? $results[$i]->domain_name : displayFriendlyDomainName($results[$i]->domain_name);
            $available_zones[$i + 1][] = $results[$i]->domain_id;
        }
    }
    $zones_list = buildSelect("user_caps[{$module_name}][access_specific_zones]", 1, $available_zones, $available_zones_perms, 5, null, true, null, 'wide_select', __('Select one or more zones'));
    return sprintf('
							<tr class="user_permissions">
								<th></th>
								<td><strong>%s</strong><br />%s</td>
							</tr>
', __('Limit access to the following zones:'), $zones_list);
}
 static function get($key, $handler = "page")
 {
     $cacheDriver = self::cacheHandler($handler);
     $return = (new $cacheDriver())->get($key);
     if (isSerialized($return)) {
         return unserialize($return);
     }
     return $return;
 }
Example #3
0
/**
 * getUserData - Retourne les informations relatives à un utilisateur
 *
 * @category userFunction
 * @param int $id Identifiant de l'utilisateur
 * @return array Array contenant les informations relatives à l'utilisateur
 *
 * @Author Ali Bellamine
 *
 * Contenu de l'array retourné :<br>
 *	['id'] => (int) Identifiant de l'utilisateur<br>
 *	['nom'] => (string) Nom de l'utilisateur<br>
 *	['prenom'] => (string) Prénom de l'utilisateur<br>
 *	['nbEtudiant'] => (string) Numéro d'étudiant de l'utilisateur<br>
 *	['mail'] => (array) Array contenant les adresses email de l'utilisateur<br>
 *	['rang'] => (int) Rang de l'utilisateur, de 0 (invité) à 4 (super administrateur)<br>
 *	['promotion']['id'] (optionnel) => (int) Identifiant de la promotion de l'utilisateur<br>
 *	['promotion']['nom'] (optionnel) => (string) Nom de la promotion de l'utilisateur<br>
 *	['service'][identifiant de l'affectation de l'utilisateur][] (optionnel) => (array) Informations relatives au service, voir {@link getServiceInfo()}<br>
 *	['service'][identifiant de l'affectation de l'utilisateur]['idAffectation] (optionnel) => (int) Identifiant de l'affectation de l'utilisateur<br>
 *	['service'][identifiant de l'affectation de l'utilisateur]['dateDebut] (optionnel) => (string) Date de début de la période d'affectation sous forme de Timestamp<br>
 *	['service'][identifiant de l'affectation de l'utilisateur]['dateFin] (optionnel) => (string) Date de fin de la période d'affectation sous forme de Timestamp<br>
 *	['service'][identifiant de l'affectation de l'utilisateur]['currentAffectation] (optionnel) => (int) 0 si l'utilisateur n'est actuellement pas affecté dans le service, 1 si il y est actuellement affecté<br>
 *	['chef'][identifiant du service][] (optionnel) => (array) Array contenant les informations relatives au service dont l'utilisateur est chef
 *
 */
function getUserData($id)
{
    /*
    	Initialisation des variables
    */
    global $db;
    // Permet l'accès à la BDD
    $erreur = array();
    $user = array();
    /*
    	On vérifie l'existance de l'utilisateur
    */
    $erreur = checkUser($id, $erreur);
    if (count($erreur) == 0) {
        // Récupérations des données utilisateur
        $sql = 'SELECT u.id userId, u.nom userNom, u.prenom userPrenom, u.nbEtudiant nbEtudiant, u.rang userRang, u.mail userMail, p.id promotionId, p.nom promotionNom
					  FROM user u
					  LEFT JOIN promotion p ON u.promotion = p.id
					  WHERE u.id = ?
					  LIMIT 1';
        $res = $db->prepare($sql);
        $res->execute(array($id));
        // On construit l'array contenant les données utilisateur
        if ($res_f = $res->fetch()) {
            $user['id'] = $res_f['userId'];
            $user['nom'] = $res_f['userNom'];
            $user['prenom'] = $res_f['userPrenom'];
            if (isSerialized($res_f['userMail'])) {
                $user['mail'] = unserialize($res_f['userMail']);
            } else {
                $user['mail'] = array($res_f['userMail']);
            }
            if (isset($res_f['nbEtudiant'])) {
                $user['nbEtudiant'] = $res_f['nbEtudiant'];
            } else {
                $user['nbEtudiant'] = '';
            }
            $user['rang'] = $res_f['userRang'];
            if (isset($res_f['promotionId'])) {
                $user['promotion']['nom'] = $res_f['promotionNom'];
                $user['promotion']['id'] = $res_f['promotionId'];
            }
            // Si il s'agit d'un étudiant
            // On récupère les affectations dans les services
            $sql = 'SELECT s.id serviceId, ae.dateDebut dateDebut, ae.dateFin dateFin, ae.id idAffectation
							  FROM affectationexterne ae
							  INNER JOIN service s ON ae.service = s.id
							  WHERE ae.userId = ?
							  ORDER BY ae.dateFin DESC';
            $res = $db->prepare($sql);
            $res->execute(array($id));
            while ($res_f = $res->fetch()) {
                $user['service'][$res_f['idAffectation']] = getServiceInfo($res_f['serviceId']);
                $user['service'][$res_f['idAffectation']]['idAffectation'] = $res_f['idAffectation'];
                $user['service'][$res_f['idAffectation']]['dateDebut'] = DatetimeToTimestamp($res_f['dateDebut']);
                $user['service'][$res_f['idAffectation']]['dateFin'] = DatetimeToTimestamp($res_f['dateFin']);
                if ($user['service'][$res_f['idAffectation']]['dateDebut'] < time() and $user['service'][$res_f['idAffectation']]['dateFin'] > time()) {
                    $user['service'][$res_f['idAffectation']]['currentAffectation'] = 1;
                } else {
                    $user['service'][$res_f['idAffectation']]['currentAffectation'] = 0;
                }
            }
            // Si il s'agit d'un chef
            // On récupère le service dont il est chef
            $sql = 'SELECT s.id serviceId
							  FROM service s
							  WHERE s.chef = ?';
            $res = $db->prepare($sql);
            $res->execute(array($id));
            while ($res_f = $res->fetch()) {
                $user['chef'][$res_f['serviceId']] = getServiceInfo($res_f['serviceId']);
            }
        }
        return $user;
    } else {
        return false;
    }
}
Example #4
0
/**
 * Returns list of available languages with some informations
 *
 * Note: For safe reasons, only the files that are readable will be indexed.
 *
 * @return array Array that contains information about available languages
 */
function i18n_getAvailableLanguages()
{
    /** @var $cfg iMSCP_Config_Handler_File */
    $cfg = iMSCP_Registry::get('config');
    if (!isset($cfg['AVAILABLE_LANGUAGES']) || !isSerialized($cfg['AVAILABLE_LANGUAGES'])) {
        i18n_buildLanguageIndex();
    }
    return unserialize($cfg['AVAILABLE_LANGUAGES']);
}
Example #5
0
/**
 * Gets the user capabilities
 *
 * @since 1.2
 * @package facileManager
 *
 * @param integer $user_id User ID to retrieve.
 * @param string $type User, group, or all
 * @return array
 */
function getUserCapabilities($user_id, $type = 'user')
{
    if ($type == 'all') {
        if ($group_id = getNameFromID($user_id, 'fm_users', 'user_', 'user_id', 'user_group')) {
            return getUserCapabilities($group_id, 'group');
        }
    }
    $user_capabilities = getNameFromID($user_id, 'fm_' . $type . 's', $type . '_', $type . '_id', $type . '_caps');
    if (isSerialized($user_capabilities)) {
        $user_capabilities = unserialize($user_capabilities);
    }
    return $user_capabilities;
}
Example #6
0
/**
 * Gets the user capabilities
 *
 * @since 1.2
 * @package facileManager
 *
 * @param integer $user_id User ID to retrieve.
 * @return array
 */
function getUserCapabilities($user_id)
{
    $user_capabilities = getNameFromID($user_id, 'fm_users', 'user_', 'user_id', 'user_caps');
    if (isSerialized($user_capabilities)) {
        $user_capabilities = unserialize($user_capabilities);
    }
    return $user_capabilities;
}
Example #7
0
/**
 * getEvalData - Retourne les informations relative à une campagne d'évaluation
 *
 * @category : evaluationFunction
 * @param int $id Identifiant de la campagne d'évaluation
 * @return array Array contenant les données relative à la campagne d'évaluation
 *
 * @Author Ali Bellamine
 *
 *	 Contenu de l'array retourné :<br>
 *		['id'] => (int) identifiant de la campagne d'évaluation<br>
 *		['nom'] => (string) nom de la campagne d'évaluation<br>
 *		['date'][debut'] => (string) Date de début de la campagne d'évaluation sous forme de Timestamp<br>
 *		['date'][fin'] => (string) Date de fin de la campagne d'évaluation sous forme de Timestamp<br>
 *		['type'][id'] => (int) Identifiant du module de la campagne d'évaluation<br>
 *		['type'][nom'] => (string) Nom du module de la campagne d'évaluation<br>
 *		['type'][dossier'] => (string) Dossier d'installation du module de la campagne d'évaluation<br>
 *		['type'][data'] => (array) Contient les données relatives au type de module d'évaluation, voir {@link getEvalTypeData()}<br>
 *		['type'][statut'] => (int) Si 0, le module d'évaluation est actuellement inactif, si 1 il est actuellement actif<br>
 *		['users'][id de l'utilisateur] => (array) Contient les informations relatives à l'utilisateur : nom, prenom, promotion, nbEtudiant, voir {@link: getUserData()}<br>
 *		['orderedUsers'][] => (array) Même informations que ci dessus, mais celles-ci sont classé par ordre de résultats de la requête SQL et non plus par id (évaluations non remplis en premier)<br>
 *		['orderedUsers']['nb'] => (int) Nombre total d'utilisateurs<br>
 *		['nb']['remplis'] => (int) nombre d'évaluations remplis<br>
 *		['nb']['total'] => (int) nombre total d'utilisateurs
 */
function getEvalData($id)
{
    /*
    	Initialisation des variables
    */
    global $db;
    // Permet l'accès à la BDD
    $erreur = array();
    $evaluation = array();
    /*
    	On vérifie l'existance de l'évaluation
    */
    $erreur = checkEvaluation($id, $erreur);
    if (count($erreur) == 0) {
        /*
        	Récupération des informations sur l'évaluation
        */
        $sql = 'SELECT e.id evaluationId, e.nom evaluationNom, e.dateDebut evaluationDateDebut, e.dateFin evaluationDateFin, t.id evaluationTypeId, t.nom evaluationTypeNom, t.nomDossier evaluationTypeDossier, t.actif evaluationTypeStatut
						FROM evaluation e
						INNER JOIN typeevaluation t ON t.id = e.type
						WHERE e.id = ?
						LIMIT 1';
        $res = $db->prepare($sql);
        $res->execute(array($id));
        while ($res_f = $res->fetch()) {
            $evaluation['id'] = $res_f['evaluationId'];
            $evaluation['nom'] = $res_f['evaluationNom'];
            $evaluation['date']['debut'] = DatetimeToTimestamp($res_f['evaluationDateDebut']);
            $evaluation['date']['fin'] = DatetimeToTimestamp($res_f['evaluationDateFin']);
            $evaluation['type']['id'] = $res_f['evaluationTypeId'];
            $evaluation['type']['nom'] = $res_f['evaluationTypeNom'];
            $evaluation['type']['dossier'] = $res_f['evaluationTypeDossier'];
            $evaluation['type']['data'] = getEvalTypeData($res_f['evaluationTypeId']);
            $evaluation['type']['statut'] = $res_f['evaluationTypeStatut'];
        }
        /*
        	Récupèration de la liste des personne assignés à l'évaluation
        */
        $sql = 'SELECT er.id idRegister, er.evaluationStatut statut, er.date date, er.userId userId, u.nom userNom, u.prenom userPrenom, u.mail userMail, p.id promotionId, p.nom promotionNom, u.nbEtudiant nbEtudiant
						FROM evaluationregister er
						INNER JOIN user u ON er.userId = u.id
						LEFT JOIN promotion p ON p.id = u.promotion
						WHERE er.evaluationId = ?
						ORDER BY er.evaluationStatut ASC, u.nom ASC, u.prenom ASC';
        $res = $db->prepare($sql);
        if ($res->execute(array($evaluation['id']))) {
            $nbEval = 0;
            $evaluation['orderedUsers'] = array();
            while ($res_f = $res->fetch()) {
                if ($res_f['statut'] == 1) {
                    $nbEval++;
                }
                $evaluation['users'][$res_f['userId']]['id'] = $res_f['userId'];
                $evaluation['users'][$res_f['userId']]['registerId'] = $res_f['idRegister'];
                $evaluation['users'][$res_f['userId']]['statut'] = $res_f['statut'];
                $evaluation['users'][$res_f['userId']]['mail'] = array();
                if (isSerialized($res_f['userMail']) && ($tempMail = unserialize($res_f['userMail']))) {
                    $firstLoop = TRUE;
                    foreach ($tempMail as $email) {
                        $evaluation['users'][$res_f['userId']]['mail'][] = $email;
                    }
                }
                $evaluation['users'][$res_f['userId']]['nom'] = $res_f['userNom'];
                $evaluation['users'][$res_f['userId']]['prenom'] = $res_f['userPrenom'];
                if (isset($res_f['promotionNom'])) {
                    $evaluation['users'][$res_f['userId']]['promotion']['id'] = $res_f['promotionId'];
                    $evaluation['users'][$res_f['userId']]['promotion']['nom'] = $res_f['promotionNom'];
                }
                $evaluation['users'][$res_f['userId']]['nbEtudiant'] = $res_f['nbEtudiant'];
                $evaluation['orderedUsers'][] = $evaluation['users'][$res_f['userId']];
                // Même liste mais ordonée
            }
            if (isset($evaluation['users'])) {
                $evaluation['nb']['total'] = count($evaluation['users']);
            } else {
                $evaluation['nb']['total'] = 0;
            }
            $evaluation['nb']['remplis'] = $nbEval;
            $evaluation['orderedUsers']['nb'] = $evaluation['nb'];
        }
        return $evaluation;
    } else {
        return false;
    }
}
Example #8
0
		**/
if (isset($_POST) && count($_POST) > 0) {
    $formData = processCCPCformData($_POST, $evaluationData);
    $erreur = $formData['erreur'];
    // On interdit les administrateurs connectés au nom d'un utilisateur de répondre au formulaire
    if ($isLogedAs) {
        $erreur['LANG_FORM_CCPC_LOGINAS_SUBMITFORBIDDEN'] = TRUE;
    }
    unset($formData['erreur']);
    /*
    	En l'absence d'erreur dans le traitement des données --> on lance l'enregistrement dans la base de donnée
    */
    if (count($erreur) == 0) {
        if (registerCCPCformData($formData)) {
            // Le formulaire a été correcterment enregistré --> on enregistre cela dans les réglages du service
            if (isSerialized(getEvaluationRegisterData())) {
                $evaluateServiceTemp = unserialize(getEvaluationRegisterData());
            } else {
                $evaluateServiceTemp = array();
            }
            if (!in_array($formData['service'], $evaluateServiceTemp)) {
                $evaluateServiceTemp[] = $formData['service'];
                setEvaluationRegisterData(serialize($evaluateServiceTemp));
                header('Location: ' . ROOT . CURRENT_FILE . '?' . http_build_query($_GET));
            }
        } else {
            // Une erreur s'est déroulé lors de l'enregistrement
            $erreur['LANG_ERROR_CCPC_UNKNOWN'] = true;
        }
    }
}
function getUnits($asset_id)
{
    if (!isSerialized($asset_id)) {
        $sql = "SELECT serial2 FROM cubit.assets WHERE id='{$asset_id}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        $units = pg_fetch_result($asset_rslt, 0);
    } else {
        $units = 1;
    }
    return $units;
}
Example #10
0
/**
 * Check for the required PHP version, and the MySQL extension or a database drop-in.
 *
 * Dies if requirements are not met.
 *
 * @access private
 * @since 1.0
 */
function checkAppVersions($single_check = true)
{
    global $fm_name;
    require ABSPATH . 'fm-includes/version.php';
    $requirement_check = null;
    $error = false;
    /** PHP Version */
    if (version_compare(PHP_VERSION, $required_php_version, '<')) {
        $message = sprintf(_('Your server is running PHP version %1$s but %2$s %3$s requires at least %4$s.'), PHP_VERSION, $fm_name, $fm_version, $required_php_version);
        if ($single_check) {
            bailOut($message);
        } else {
            $requirement_check .= displayProgress("PHP >= {$required_php_version}", false, 'display', $message);
            $error = true;
        }
    } else {
        if (!$single_check) {
            $requirement_check .= displayProgress("PHP >= {$required_php_version}", true, 'display');
        }
    }
    /** PHP Extensions */
    $required_php_extensions = array('mysql', 'mysqli', 'curl', 'posix', 'filter', 'json');
    foreach ($required_php_extensions as $extension) {
        if (!extension_loaded($extension)) {
            $message = sprintf(_('Your PHP installation appears to be missing the %1s extension which is required by %2s.'), $extension, $fm_name);
            if ($single_check) {
                bailOut($message);
            } else {
                $requirement_check .= displayProgress(_(sprintf('PHP %1s Extension', $extension)), false, 'display', $message);
                $error = true;
            }
        } else {
            if (!$single_check) {
                $requirement_check .= displayProgress(_(sprintf('PHP %1s Extension', $extension)), true, 'display');
            }
        }
    }
    /** Apache mod_rewrite module */
    if (function_exists('apache_get_modules')) {
        if (!in_array('mod_rewrite', apache_get_modules())) {
            $message = sprintf(_('Your Apache installation appears to be missing the mod_rewrite module which is required by %1s.'), $fm_name);
            if ($single_check) {
                bailOut($message);
            } else {
                $requirement_check .= displayProgress(_('Apache mod_rewrite Loaded'), false, 'display', $message);
                $error = true;
            }
        } else {
            if (!$single_check) {
                $requirement_check .= displayProgress(_('Apache mod_rewrite Loaded'), true, 'display');
            }
        }
    }
    /** .htaccess file */
    if (!defined('FM_NO_HTACCESS')) {
        if (!file_exists(ABSPATH . '.htaccess')) {
            if (is_writeable(ABSPATH)) {
                file_put_contents(ABSPATH . '.htaccess', '<IfModule mod_headers.c>
	<FilesMatch "\\.(js|css|txt)$">
		Header set Cache-Control "max-age=7200"
	</FilesMatch>
	<FilesMatch "\\.(jpe?g|png|gif|ico)$">
		Header set Cache-Control "max-age=2592000"
	</FilesMatch>
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

');
            } else {
                if ($single_check) {
                    bailOut(sprintf(_('I cannot create the missing %1s.htaccess which is required by %2s so please create it with the following contents:'), ABSPATH, $fm_name) . '<textarea rows="8">&lt;IfModule mod_headers.c&gt;
	&lt;FilesMatch "\\.(js|css|txt)$"&gt;
		Header set Cache-Control "max-age=7200"
	&lt;/FilesMatch&gt;
	&lt;FilesMatch "\\.(jpe?g|png|gif|ico)$"&gt;
		Header set Cache-Control "max-age=2592000"
	&lt;/FilesMatch&gt;
&lt;/IfModule&gt;

&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
&lt;/IfModule&gt;
</textarea>');
                } else {
                    $requirement_check .= displayProgress(_('.htaccess File Present'), false, 'display');
                    $error = true;
                }
            }
        } else {
            if (!$single_check) {
                $requirement_check .= displayProgress(_('.htaccess File Present'), true, 'display');
            }
        }
    }
    /** Test rewrites */
    if (!defined('INSTALL')) {
        if (dns_get_record($_SERVER['SERVER_NAME'], DNS_A + DNS_AAAA)) {
            $test_output = getPostData($GLOBALS['FM_URL'] . 'admin-accounts.php?verify', array('module_type' => 'CLIENT'));
            $test_output = isSerialized($test_output) ? unserialize($test_output) : $test_output;
            if (strpos($test_output, 'Account is not found.') === false) {
                $message = sprintf(_('The required .htaccess file appears to not work with your Apache configuration which is required by %1s.'), $fm_name);
                if ($single_check) {
                    bailOut($message);
                } else {
                    $requirement_check .= displayProgress(_('Test Rewrites'), false, 'display', $message);
                    $error = true;
                }
            } else {
                if (!$single_check) {
                    $requirement_check .= displayProgress(_('Test Rewrites'), true, 'display');
                }
            }
        }
    }
    if ($error) {
        $requirement_check = sprintf('
			<div id="window">
			<table class="form-table">%s</table>
			<p class="step"><a href="%s" class="button">%s</a></p></div>', $requirement_check, $_SERVER['PHP_SELF'], _('Try Again'));
    } else {
        $requirement_check = null;
    }
    return $requirement_check;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($asset_id, "num", 1, 9, "Invalid asset id.");
    $v->isOk($ex_year, "num", 4, 4, "Invalid expected date (year)");
    $v->isOk($ex_month, "num", 1, 2, "Invalid expected date (month)");
    $v->isOk($ex_day, "num", 1, 2, "Invalid expected date (day)");
    $v->isOk($description, "string", 0, 255, "Invalid description.");
    $v->isOk($qty, "num", 1, 9, "Invalid qty.");
    if (!isSerialized($asset_id) && $qty <= 0) {
        $v->addError(0, "Invalid Quantity.");
    }
    if (getUnits($asset_id) < $qty) {
        $v->addError(0, "Not enough items available.");
    }
    if ($v->isError()) {
        return enter($v->genErrors());
    }
    $ex_date = dateFmt($ex_year, $ex_month, $ex_day);
    $notes = base64_encode($notes);
    $sql = "SELECT id, des, serial, serial2 FROM cubit.assets\r\n\t\t\t\tWHERE id='{$asset_id}'";
    $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
    $asset_data = pg_fetch_array($asset_rslt);
    pglib_transaction("BEGIN");
    $sql = "INSERT INTO cubit.workshop (stkcod, description, notes, status,\r\n\t\t\t\tserno, cdate, active, asset_id, e_date, qty)\r\n\t\t\t\tVALUES ('{$asset_data['des']}', '{$description}', '{$notes}', 'Present',\r\n\t\t\t\t\t'{$asset_data['serial']}', CURRENT_DATE, 'true',\r\n\t\t\t\t\t'{$asset_data['id']}', '{$ex_date}', '{$qty}')";
    $ws_rslt = db_exec($sql) or errDie("Unable to add workshop item.");
    $sql = "UPDATE cubit.assets SET remaction='Workshop' WHERE id='{$asset_data['id']}'";
    db_exec($sql) or errDie("Unable to update assets.");
    if (!isSerialized($asset_id)) {
        $new_qty = $asset_data["serial2"] - $qty;
        $sql = "UPDATE cubit.assets SET serial2='{$new_qty}'\r\n\t\t\t\t\tWHERE id='{$asset_data['id']}'";
        db_exec($sql) or errDie("Unable to update assets.");
    }
    pglib_transaction("COMMIT");
    $OUTPUT = "<h3>Book Asset to Workshop</h3>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Write</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td><li>Successfully booked asset to the workshop.</li></td>\r\n\t\t</tr>\r\n\t</table>";
    return $OUTPUT;
}
function run()
{
    extract($_REQUEST);
    pglib_transaction("BEGIN");
    // Retrieve outstanding rentals
    $sql = "\n\tSELECT id, user_id, username, order_num, subtotal, vat, total, discount,\n\t\tdelivery, customers.cusnum, surname, addr1, addr2, addr3, accno,\n\t\tvatnum, tel, discount_perc, timestamp, deposit\n\tFROM cubit.hire_trans\n\t\tLEFT JOIN cubit.customers ON hire_trans.cusnum=customers.cusnum\n\t\tLEFT JOIN cubit.users ON hire_trans.user_id=users.userid\n\tWHERE user_id='{$user_id}' AND done='y'";
    $rental_rslt = db_exec($sql) or errDie("Unable to retrieve rentals.");
    $hire_nums = array();
    while ($rental_data = pg_fetch_array($rental_rslt)) {
        $deptid = 2;
        $time = strtotime($rental_data["timestamp"]);
        $sql = "SELECT deptname FROM exten.departments WHERE deptid='{$deptid}'";
        $deptname_rslt = db_exec($sql) or errDie("Unable to retrieve department.");
        $deptname = pg_fetch_result($deptname_rslt, 0);
        // Create hire note
        $sql = "\n\t\tINSERT INTO hire.hire_invoices (deptid, cusnum, cordno, ordno,\n\t\t\tchrgvat, terms, salespn, odate, printed, comm, done, username,\n\t\t\tdeptname, cusacc, cusname, surname, cusaddr, cusordno, cusvatno,\n\t\t\tprd, invnum, div, prints, disc, discp, delchrg, subtot, traddisc,\n\t\t\tbalance, vat, total, discount, delivery, nbal, rdelchrg, serd,\n\t\t\tpcash, pcheque, pcc, rounding, pchange, delvat, pcredit, vatnum,\n\t\t\ttelno, systime, deposit_type, deposit_amt, custom_txt, collection,\n\t\t\tbranch_addr, timestamp, hire_invid, revision)\n\t\tVALUES ('{$deptid}', '{$rental_data['cusnum']}', '', '', 'inc', '0', '2',\n\t\t\t'" . date("Y-m-d", $time) . "', 'y', '', 'y', '{$rental_data['username']}',\n\t\t\t'{$deptname}', '{$rental_data['accno']}', '', '{$rental_data['surname']}',\n\t\t\t'{$rental_data['addr1']}', '{$rental_data['order_num']}',\n\t\t\t'{$rental_data['vatnum']}', '" . PRD_DB . "', '{$rental_data['id']}',\n\t\t\t'" . USER_DIV . "', '0', '{$rental_data['discount']}',\n\t\t\t'{$rental_data['discount_perc']}', '{$rental_data['delivery']}',\n\t\t\t'{$rental_data['subtotal']}', '{$rental_data['discount']}', '0.00',\n\t\t\t'{$rental_data['vat']}', '{$rental_data['total']}',\n\t\t\t'{$rental_data['discount']}', '{$rental_data['delivery']}', '0.00', '0.00',\n\t\t\t'', '100', '100', '100', '100', '100', '0', '0.00',\n\t\t\t'{$rental_data['vatnum']}', '{$rental_data['tel']}',\n\t\t\t'{$rental_data['timestamp']}', 'CSH', '{$rental_data['deposit']}', '',\n\t\t\t'Client Collect', '0', current_timestamp, '0', '0')";
        db_exec($sql) or errDie("Unable to create hire note.");
        $invid = pglib_lastid("hire.hire_invoices", "invid");
        $hire_nums[$rental_data["id"]] = $invid;
        // Do deposit transaction if required
        if ($rental_data["deposit"] > 0) {
            $cash_on_hand = qryAccountsNum("7200", "000");
            $cash_on_hand = $cash_on_hand["accid"];
            $cust_control = qryAccountsNum("6400", "000");
            $cust_control = $cust_control["accid"];
            $refnum = getRefnum();
            writetrans($cash_on_hand, $cust_control, date("Y-m-d", $time), $refnum, $rental_data["deposit"], "Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}");
            $sql = "\n\t\t\tINSERT INTO hire.cash (invid, cash)\n\t\t\tVALUES ('{$invid}', '{$rental_data['deposit']}')";
            db_exec($sql) or errDie("Unable to add cash to hire.");
            // Make ledger record
            custledger($rental_data["cusnum"], $cust_control, date("Y-m-d", $time), $invid, "Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}", $rental_data["deposit"], "c");
            custCT($rental_data["deposit"], $rental_data["cusnum"], date("Y-m-d", $time));
            // Turn the amount around to a negative
            $stmnt_amt = $rental_data["deposit"] - $rental_data["deposit"] * 2;
            // Record the payment on the statement
            $sql = "\n\t\t\tINSERT INTO cubit.stmnt(cusnum, invid, docref, amount, date, type,\n\t\t\t\tdiv)\n\t\t\tVALUES('{$rental_data['cusnum']}', '{$invid}', '{$rental_data['id']}',\n\t\t\t\t'{$stmnt_amt}', '" . date("Y-m-d", $time) . "',\n\t\t\t\t'Cash Receipt for " . CUR . "{$rental_data['deposit']} from " . "{$rental_data['surname']} for Deposit on Hire Note {$rental_data['id']}',\n\t\t\t\t'" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to add deposit to statement");
            // Update customer balance
            $sql = "\n\t\t\tUPDATE cubit.customers SET balance=balance-'{$rental_data['deposit']}'\n\t\t\tWHERE cusnum='{$rental_data['cusnum']}'";
            db_exec($sql) or errDie("Unable to update customer balance.");
            $sql = "\n\t\t\tUPDATE hire.hire_invoices SET deposit_amt='0'\n\t\t\tWHERE invid='{$invid}'";
            db_exec($sql) or errDie("Unable to retrieve hire invoices.");
        }
        // Retrieve items on this invoice
        $sql = "\n\t\tSELECT asset_id, basis, from_date, to_date, half_day, qty,\n\t\t\tweekends, total_days, total\n\t\tFROM cubit.hire_trans_items\n\t\tWHERE hire_id='{$rental_data['id']}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        while ($item_data = pg_fetch_array($item_rslt)) {
            $unitcost = $item_data["total"] / $item_data["qty"];
            // Decide which basis to use
            $hours = 0;
            $weeks = 0;
            $days = 0;
            $months = 0;
            $total_days = 0;
            switch ($item_data["basis"]) {
                case "per_hour":
                    $hours = $item_data["total_days"];
                    break;
                case "per_day":
                    $days = $item_data["total_days"];
                    $total_days = $item_data["total_days"];
                    break;
                case "per_week":
                    $week = $item_data["total_days"];
                    break;
                case "per_month":
                    $months = $item_data["total_days"];
                    break;
            }
            // Convert booleans into something we can use
            $half_day = $item_data["half_day"] == "t" ? 1 : 0;
            $weekends = $item_data["weekends"] == "t" ? 1 : 0;
            $sql = "\n\t\t\tINSERT INTO hire.hire_invitems (invid, qty, amt, unitcost,\n\t\t\t\tfrom_date, to_date, asset_id, basis, hours, weeks, days,\n\t\t\t\tmonths, half_day, weekends, total_days)\n\t\t\tVALUES ('{$invid}', '{$item_data['qty']}', '{$item_data['total']}',\n\t\t\t\t'{$unitcost}', '{$item_data['from_date']}', '{$item_data['to_date']}',\n\t\t\t\t'{$item_data['asset_id']}', '{$item_data['basis']}', '{$hours}',\n\t\t\t\t'{$weeks}', '{$days}', '{$months}', '{$half_day}', '{$weekends}',\n\t\t\t\t'{$total_days}')";
            db_exec($sql) or errDie("Unable to create rental items.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\n\t\t\tINSERT INTO hire.assets_hired (invid, asset_id, qty, hired_time,\n\t\t\t\tcust_id, item_id, invnum, value, basis, discount, weekends)\n\t\t\tVALUES ('{$invid}', '{$item_data['asset_id']}', '{$item_data['qty']}',\n\t\t\t\t'{$rental_data['timestamp']}', '{$rental_data['cusnum']}', '{$item_id}',\n\t\t\t\t'{$rental_data['id']}', '{$item_data['total']}', '{$item_data['basis']}',\n\t\t\t\t'0.00', '{$weekends}')";
            db_exec($sql) or errDie("Unable to add to assets hired.");
        }
    }
    // Run invoices ----------------------------------------------------------
    $sql = "\n\tSELECT id, hire_id, customers.cusnum, order_num, discount_perc, discount,\n\t\tsubtotal, total, vat, timestamp, user_id, surname, addr1, vatnum,\n\t\tusername, delivery\n\tFROM cubit.hire_invoice_trans\n\t\tLEFT JOIN cubit.customers ON hire_invoice_trans.cusnum=customers.cusnum\n\t\tLEFT JOIN cubit.users ON hire_invoice_trans.user_id=users.userid\n\tWHERE done='y' AND user_id='{$user_id}' AND hire_id > 0";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    while ($inv_data = pg_fetch_array($inv_rslt)) {
        $hire_sales = qryAccountsNum("1050", "000");
        $cust_control = qryAccountsNum("6400", "000");
        $cash_on_hand = qryAccountsNum("7200", "000");
        $hire_sales = $hire_sales["accid"];
        $cust_control = $cust_control["accid"];
        $cash_on_hand = $cash_on_hand["accid"];
        $time = strtotime($inv_data["timestamp"]);
        $sql = "\n\t\tINSERT INTO cubit.nons_invoices (cusname, cusaddr, cusvatno,\n\t\t\tchrgvat, sdate, done, username, prd, invnum, div, remarks, cusid,\n\t\t\tage, typ, subtot, balance, vat, total, descrip, ctyp, accid,\n\t\t\tfbalance, fsubtot, cordno, terms, odate, systime, bankid,\n\t\t\tcusordno, ncdate, cusnum, discount, delivery, hire_invid,\n\t\t\tcash, cheque, credit)\n\t\tVALUES ('{$inv_data['surname']}', '{$inv_data['addr1']}', '{$inv_data['vatnum']}',\n\t\t\t'yes', '" . date("Y-m-d", $time) . "', 'y', '{$inv_data['username']}',\n\t\t\t'" . PRD_DB . "', '{$inv_data['id']}', '" . USER_DIV . "', '',\n\t\t\t'{$inv_data['cusnum']}', '0', 'inv', '{$inv_data['subtotal']}',\n\t\t\t'{$inv_data['total']}', '{$inv_data['vat']}', '{$inv_data['total']}', '', 's',\n\t\t\t'{$hire_sales}', '0.00', '0.00', '{$inv_data['order_num']}', '0',\n\t\t\t'" . date("Y-m-d", $time) . "', current_timestamp,\n\t\t\t'" . cust_bank_id($inv_data["cusnum"]) . "', '{$inv_data['order_num']}',\n\t\t\t'" . date("Y-m-d", $time) . "', '{$inv_data['cusnum']}',\n\t\t\t'{$inv_data['discount']}', '{$inv_data['delivery']}',\n\t\t\t'" . $hire_nums[$inv_data["hire_id"]] . "', '{$inv_data['total']}', '0', '0')";
        db_exec($sql) or errDie("Unable to create non stock invoice.");
        $invid = lastinvid();
        $sql = "\n\t\tSELECT hire_invoice_items_trans.id, asset_id, basis, from_date,\n\t\t\tto_date, half_day, qty, weekends, total_days, total,\n\t\t\tserial, des, grpid\n\t\tFROM cubit.hire_invoice_items_trans\n\t\t\tLEFT JOIN cubit.assets\n\t\t\t\tON hire_invoice_items_trans.asset_id=assets.id\n\t\tWHERE trans_id='{$inv_data['id']}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        while ($item_data = pg_fetch_array($item_rslt)) {
            $unitcost = $item_data["total"] / $item_data["qty"];
            $item_id = 0;
            $sql = "\n\t\t\tSELECT {$item_data['basis']} FROM hire.basis_prices\n\t\t\tWHERE assetid='{$item_data['asset_id']}'";
            $rate_rslt = db_exec($sql) or errDie("Unable to retrieve rate.");
            $rate = pg_fetch_result($rate_rslt, 0);
            $rate = empty($rate) ? 0.0 : $rate;
            $sql = "\n\t\t\tSELECT serial, des FROM cubit.assets\n\t\t\tWHERE id='{$item_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $asset_data = pg_fetch_array($asset_rslt);
            $sql = "\n\t\t\tINSERT INTO hire.hire_nons_inv_items (invid, qty, description, div,\n\t\t\t\tamt, unitcost, accid, vatex, cunitcost, asset_id, item_id,\n\t\t\t\thired_days, rate)\n\t\t\tVALUES ('{$invid}', '{$item_data['qty']}', '({$asset_data['serial']}) " . "{$asset_data['des']} hired from {$item_data['from_date']} to " . "{$item_data['to_date']}.', '" . USER_DIV . "', '{$item_data['total']}',\n\t\t\t\t'{$unitcost}', '{$hire_sales}', '2', '{$unitcost}',\n\t\t\t\t'{$item_data['asset_id']}', '{$item_id}', '{$item_data['total_days']}',\n\t\t\t\t'{$rate}')";
            db_exec($sql) or errDie("Unable to create invoice item.");
            // Add up revenue
            $sql = "\n\t\t\tINSERT INTO hire.revenue (group_id, asset_id, total, discount,\n\t\t\t\thire_invnum, inv_invnum, cusname)\n\t\t\tVALUES ('{$item_data['grpid']}', '{$item_data['asset_id']}',\n\t\t\t\t'{$item_data['total']}', '0', '0',\n\t\t\t\t'0', '{$inv_data['surname']}')";
            db_exec($sql) or errDie("Unable to update revenue");
            $sql = "\n\t\t\tUPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP\n\t\t\t\tWHERE item_id='{$item_data['id']}'";
            db_exec($sql) or errDie("Unable to update hired assets.");
            $sql = "\n\t\t\tSELECT serial2 FROM cubit.assets\n\t\t\tWHERE id='{$item_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset");
            $asset_data = pg_fetch_array($asset_rslt);
            if (!isSerialized($item_data["asset_id"])) {
                $new_qty = $asset_data["serial2"] + $item_data["qty"];
                $sql = "\n\t\t\t\tUPDATE cubit.assets SET serial2=(serial2::numeric + '{$item_data['qty']}')\n\t\t\t\tWHERE id='{$item_data['asset_id']}'";
                db_exec($sql) or errDie("Unable to update asset qty.");
            }
        }
        $refnum = getRefnum();
        writetrans($cust_control, $hire_sales, date("Y-m-d", $time), $refnum, $inv_data["total"], "Non Stock Sales on invoice No. {$inv_data['id']} " . "customer {$inv_data['surname']}");
        // Sales record
        $sql = "\n\t\tINSERT INTO cubit.salesrec(edate, invid, invnum, debtacc, vat, total,\n\t\t\ttyp, div)\n\t\tVALUES('" . date("Y-m-d", $time) . "', '{$invid}', '{$inv_data['id']}',\n\t\t\t'{$cust_control}', '{$inv_data['vat']}', '{$inv_data['total']}', 'non',\n\t\t\t'" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to create sales record.");
        // Vat record
        vatr(2, date("Y-m-d", $time), "OUTPUT", '01', $refnum, "Non-Stock Sales, invoice No.{$inv_data['id']}", $inv_data["total"], $inv_data["vat"]);
        // Add to statement
        $sql = "\n\t\tINSERT INTO cubit.stmnt (cusnum, invid, docref, amount, date, type, div)\n\t\tVALUES ('{$inv_data['cusnum']}', '{$invid}', '{$inv_data['order_num']}',\n\t\t\t'{$inv_data['total']}', '" . date("Y-m-d", $time) . "',\n\t\t\t'Hire Invoice {$inv_data['id']}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to add to statement.");
        // Update customer balance
        $sql = "\n\t\tUPDATE customers SET balance = (balance + '{$inv_data['total']}')\n\t\tWHERE cusnum='{$inv_data['cusnum']}' AND div='" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update customer balance.");
        custledger($inv_data["cusnum"], $hire_sales, date("Y-m-d", $time), $invid, "Hire Invoice No. {$inv_data['id']}", $inv_data["total"], "d");
        custDT($inv_data["total"], $inv_data["cusnum"], date("Y-m-d", $time));
    }
    // Clear outstanding tables
    $sql = "DELETE FROM cubit.hire_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (1)");
    $sql = "DELETE FROM cubit.hire_trans_items";
    db_exec($sql) or errDie("Unable to remove outstanding (2)");
    $sql = "DELETE FROM cubit.hire_invoice_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (3)");
    $sql = "DELETE FROM cubit.hire_invoice_items_trans";
    db_exec($sql) or errDie("Unable to remove outstanding (4)");
    pglib_transaction("COMMIT");
    return enter();
}
 public function populateMetadata($guid)
 {
     $this->guid = $guid;
     $query = "SELECT * FROM `entities` WHERE `guid` = '{$guid}' LIMIT 1";
     $results_array = Dbase::getResultsArray($query);
     $this->type = ucfirst($results_array[0]['type']);
     $type = strtolower($this->type);
     $query = "SELECT * FROM `{$type}` WHERE `guid`='{$this->guid}' LIMIT 1";
     $results = Dbase::getResultsArray($query);
     if (!empty($results)) {
         foreach ($results[0] as $key => $value) {
             if ($key != "id" && $key != "guid" && $key != "type") {
                 if (isSerialized(stripslashes($value))) {
                     $value = unserialize(stripslashes($value));
                 }
                 if (!is_array($value) && !is_bool($value)) {
                     //                        $this->$key = nl2br(stripslashes($value));
                     $this->{$key} = stripslashes($value);
                 } else {
                     $this->{$key} = $value;
                 }
             }
         }
     }
 }
Example #14
0
/** fM v1.2-beta1 **/
function fmUpgrade_1201($database)
{
    global $fmdb, $fm_name;
    $success = true;
    /** Prereq */
    $success = $GLOBALS['running_db_version'] < 28 ? fmUpgrade_107($database) : true;
    if ($success) {
        /** Schema change */
        $table[] = "ALTER TABLE  {$database}.`fm_options` ADD  `module_name` VARCHAR( 255 ) NULL AFTER  `account_id` ";
        $table[] = "ALTER TABLE  `fm_users` ADD  `user_caps` TEXT NULL AFTER  `user_auth_type` ";
        /** Create table schema */
        if (count($table) && $table[0]) {
            foreach ($table as $schema) {
                $fmdb->query($schema);
                if (!$fmdb->result || $fmdb->sql_errors) {
                    return false;
                }
            }
        }
        $inserts = null;
        if (count($inserts) && $inserts[0] && $success) {
            foreach ($inserts as $query) {
                $fmdb->query($query);
                if ($fmdb->last_error) {
                    echo $fmdb->last_error;
                    return false;
                }
            }
        }
        /** Update fm_options */
        $version_check = getOption($fm_name . '_version_check');
        if ($version_check !== false) {
            if (!setOption('version_check', $version_check, 'auto', true, 0, $fm_name)) {
                return false;
            }
            $query = "DELETE FROM {$database}.`fm_options` WHERE option_name='{$fm_name}_version_check'";
            $fmdb->query($query);
            if (!$fmdb->result || $fmdb->sql_errors) {
                return false;
            }
        }
        $modules = getAvailableModules();
        if (count($modules)) {
            foreach ($modules as $module_name) {
                $module_version = getOption($module_name . '_version');
                if ($module_version !== false) {
                    if (!setOption('version', $module_version, 'auto', false, 0, $module_name)) {
                        return false;
                    }
                }
                $module_version_check = getOption($module_name . '_version_check');
                if ($module_version_check !== false) {
                    if (!setOption('version_check', $module_version_check, 'auto', true, 0, $module_name)) {
                        return false;
                    }
                }
                $module_client_version = getOption($module_name . '_client_version');
                if ($module_client_version !== false) {
                    if (!setOption('client_version', $module_client_version, 'auto', false, 0, $module_name)) {
                        return false;
                    }
                }
                $query = "DELETE FROM {$database}.`fm_options` WHERE option_name LIKE '{$module_name}%_version%'";
                $fmdb->query($query);
                if (!$fmdb->result || $fmdb->sql_errors) {
                    return false;
                }
            }
        }
        /** Update user capabilities */
        $fm_user_caps[$fm_name] = array('do_everything' => '<b>Super Admin</b>', 'manage_modules' => 'Module Management', 'manage_users' => 'User Management', 'run_tools' => 'Run Tools', 'manage_settings' => 'Manage Settings');
        if (!setOption('fm_user_caps', $fm_user_caps)) {
            return false;
        }
        $fmdb->get_results("SELECT * FROM `fm_users`");
        if ($fmdb->num_rows) {
            $count = $fmdb->num_rows;
            $result = $fmdb->last_result;
            for ($i = 0; $i < $count; $i++) {
                $user_caps = null;
                /** Update user capabilities */
                $j = 1;
                foreach ($fm_user_caps[$fm_name] as $slug => $trash) {
                    if ($j & $result[$i]->user_perms) {
                        $user_caps[$fm_name][$slug] = 1;
                    }
                    $j = $j * 2;
                }
                $fmdb->query("UPDATE fm_users SET user_caps = '" . serialize($user_caps) . "' WHERE user_id=" . $result[$i]->user_id);
                if (!$fmdb->result || $fmdb->sql_errors) {
                    return false;
                }
            }
        }
        $fmdb->query("ALTER TABLE `fm_users` DROP `user_perms`;");
        if (!$fmdb->result || $fmdb->sql_errors) {
            return false;
        }
        /** Temporarily move the module user capabilities to fm_users */
        $fmdb->get_results("SELECT * FROM `fm_perms`");
        if ($fmdb->num_rows) {
            $count = $fmdb->num_rows;
            $result = $fmdb->last_result;
            for ($i = 0; $i < $count; $i++) {
                if (!($user_info = getUserInfo($result[$i]->user_id))) {
                    continue;
                }
                /** Update user capabilities */
                $user_caps = isSerialized($user_info['user_caps']) ? unserialize($user_info['user_caps']) : $user_info['user_caps'];
                $user_caps[$result[$i]->perm_module] = isSerialized($result[$i]->perm_extra) ? unserialize($result[$i]->perm_extra) : $result[$i]->perm_extra;
                $user_caps[$result[$i]->perm_module]['imported_perms'] = $result[$i]->perm_value;
                $fmdb->query("UPDATE fm_users SET user_caps = '" . serialize($user_caps) . "' WHERE user_id=" . $result[$i]->user_id);
                if (!$fmdb->result || $fmdb->sql_errors) {
                    return false;
                }
            }
        }
        $fmdb->query("DROP TABLE `fm_perms`");
        if (!$fmdb->result || $fmdb->sql_errors) {
            return false;
        }
    }
    upgradeConfig('fm_db_version', 32, false);
    return $success;
}
function cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    // 	if(isset($stkaccs)){
    // 		foreach($stkaccs as $key => $accid){
    // 			$v->isOk ($accid, "num", 1, 20, "Invalid Item Account number.");
    // 		}
    // 	}else{
    // 		$v->isOk ($invid, "num", 0, 0, "Invalid Item Account number.");
    // 	}
    if (!isset($description) && !count($description)) {
        $v->addError(0, "No items selected.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    // Update descriptions
    foreach ($description as $key => $value) {
        $sql = "UPDATE hire.hire_nons_inv_items SET description='{$value}' WHERE id='{$key}'";
        db_exec($sql) or errDie("Unable to update descriptions.");
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.");
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT basis, hours, weeks,\r\n\t\t\t\t\textract('epoch' from from_date) AS e_from,\r\n\t\t\t\t\textract('epoch' from to_date) AS e_to\r\n\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tWHERE id='{$stk['item_id']}'";
        $hired_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $hired_data = pg_fetch_array($hired_rslt);
        // --------------------------------------------------------------------
        $sql = "SELECT * FROM cubit.assets WHERE id='{$stk['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $sql = "SELECT traddisc FROM hire.hire_invoices WHERE invid='{$inv['hire_invid']}'";
        $disc_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
        $traddisc = pg_fetch_result($disc_rslt, 0);
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP\r\n\t\t\t\tWHERE item_id='{$stk['item_id']}'";
        db_exec($sql) or errDie("Unable to update hired assets.");
        if (isset($monthly) && !$monthly) {
            if (!isSerialized($asset_data["id"])) {
                $new_qty = $asset_data["serial2"] + $stk["qty"];
                $sql = "UPDATE cubit.assets SET serial2='{$new_qty}' WHERE id='{$stk['asset_id']}'";
                db_exec($sql) or errDie("Unable to update assets.");
            }
            $hire_num = getHirenum($inv["hire_invid"]);
            if ($hire_num) {
                $sql = "SELECT * FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
                while ($hi_data = pg_fetch_array($hi_rslt)) {
                    $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\t\t\tWHERE invid='{$hi_data['invid']}'";
                    db_exec($sql) or errDie("Unable to remove old items.");
                }
                $sql = "DELETE FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "DELETE FROM hire.monthly_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\t\tWHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to update return time.");
            }
            $sql = "DELETE FROM hire.hire_invitems WHERE id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove returned item.");
            $sql = "DELETE FROM hire.monthly_invitems WHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\tWHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "DELETE FROM hire.monthly_invoices\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
            $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
        }
        $stkacc = $stkaccs[$stk['id']];
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                // Seems only this one is used for our hiring purposes
                $totstkamt[$stkacc] = $stk['amt'];
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        }
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE hire.hire_nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // 		$time_from = "$from_day-$from_month-$from_year $from_hour:$from_minute";
        // 		$time_to = "$to_day-$to_month-$to_year $to_hour:$to_minute";
        if ($hired_data["weeks"]) {
            $hired_days = sprint($hired_data["weeks"] * 7);
        } elseif ($hired_data["e_from"] > 0) {
            $secs = $hired_data["e_to"] - $hired_data["e_from"];
            $hired_days = sprint($secs / (60 * 60 * 24) + 1);
        } elseif ($hired_data["hours"]) {
            $secs = $hired_data["hours"] / 24;
            $hired_days = sprint($secs);
        } else {
            $hired_days = 0;
        }
        $hired_days = floor($hired_days);
        switch ($hired_data["basis"]) {
            case "per_hour":
                $basis = "Hourly";
                $basis_s = "hour";
                $basis_p = "per_hour";
                break;
            case "per_day":
                $basis = "Daily";
                $basis_s = "day";
                $basis_p = "per_day";
                break;
            case "per_week":
                $basis = "Weekly";
                $basis_s = "week";
                $basis_p = "per_week";
        }
        $rate = basisPrice($inv["cusnum"], $stk["asset_id"], $basis_p);
        if (empty($rate)) {
            $rate = "0.00";
        }
        $sql = "UPDATE hire.hire_nons_inv_items SET hired_days='{$hired_days}',\r\n\t\t\trate='{$rate}' WHERE id='{$stk['id']}'";
        db_exec($sql) or errDie("Unable to save to items.");
        $products[$page][] = "<tr valign=top>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$hired_days}&nbsp;</td>\r\n\t\t\t<td align='right' style='border-right: 2px solid #000'>({$basis}) " . sprint($rate) . " &nbsp;</td>\r\n\t\t\t<td align='right'>" . CUR . sprint($stk["amt"]) . "&nbsp;</td>\r\n\t\t</tr>";
        $i++;
    }
    $inv['chrgvat'] = $t;
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "<tr>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n  \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td>&nbsp;</td>\r\n \t\t\t</tr>";
        }
    }
    $sql = "INSERT INTO hire.hires (inv_id, user_id, cust_id, from_time)\r\n\t\t\tVALUES ('{$inv['invid']}', " . USER_ID . ", '{$inv['cusnum']}', CURRENT_TIMESTAMP)";
    db_exec($sql) or errDie("Unable to create new hire.");
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    if (isset($bankid)) {
        $bankid += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class=err>Bank not Found.</li>";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $deptd = pg_fetch_array($deptRslt);
        }
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $rd = db_exec($Sl) or errDie("Unable to get data.");
        $data = pg_fetch_array($rd);
        $BA = $data['accnum'];
    }
    $tot_post = 0;
    # bank  % cust
    if ($ctyp == 's') {
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.</li>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $wamt += $inv["delivery"] / count($totstkamt);
            $wamt -= $inv["discount"] / count($totstkamt);
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($dept['debtacc'], $stkacc, $td, $refnum, $SUBTOT, "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        $sdate = date("Y-m-d");
    } else {
        if (!isset($accountc)) {
            $accountc = 0;
        }
        if (!isset($dept['pca'])) {
            $accountc += 0;
            $dept['pca'] = $accountc;
            $dept['debtacc'] = $accountc;
        }
        if (isset($bankid)) {
            $dept['pca'] = $BA;
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            if (!isset($cust['surname'])) {
                $cust['surname'] = $inv['cusname'];
                $cust['addr1'] = $inv['cusaddr'];
            }
            # Debit Customer and Credit stock
            $wamt += $inv["delivery"] / count($totstkamt);
            $tot_post += $wamt;
            writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        if (isset($bankid)) {
            db_connect();
            $bankid += 0;
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
            $sql = "UPDATE cubit.hire_nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "UPDATE cubit.nons_invoices SET cusid = '{$cusnum}', ctyp = '{$ctyp}', cusname = '{$cus['surname']}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}', balance = total WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        //
        // 		# Record the payment on the statement
        // 		$sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('$cusnum', '$real_invid', '$inv[docref]', '$TOTAL','$inv[odate]', 'Non-Stock Invoice', '".USER_DIV."')";
        // 		$stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        //
        // 		# Record the payment on the statement
        // 		$sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('$cusnum', '$real_invid', '$inv[docref]', '$TOTAL', '$TOTAL','$inv[sdate]', 'Non-Stock Invoice', '".USER_DIV."')";
        // 		$stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        //
        // 		# Update the customer (make balance more)
        // 		$sql = "UPDATE customers SET balance = (balance + '$TOTAL'::numeric(13,2)) WHERE cusnum = '$cusnum' AND div = '".USER_DIV."'";
        // 		$rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.",SELF);
        //
        // 		# Make ledge record
        // 		custledger($cusnum,$stkacc , $td, $real_invid, "Non Stock Invoice No. $real_invid", $TOTAL, "d");
        // 		custDT($TOTAL, $cusnum, $td);
        //
        // 		$tot_dif=sprint($tot_post-$TOTAL);
        if (!isset($tot_dif)) {
            $tot_dif = 0;
        }
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    } else {
        $date = date("Y-m-d");
        $sql = "UPDATE cubit.nons_invoices SET balance=total, cusname = '{$cust['surname']}', accid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    }
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$cusnum}','{$na}','Non stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    // Customer Statement -----------------------------------------------------
    # Record the payment on the statement
    $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div)\r\n\t\t\tVALUES('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$inv['odate']}', 'Hire Invoice H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record");
    # Record the payment on the statement
    $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance,\r\n\t\t\t\tdate, type, div)\r\n\t\t\tVALUES ('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$TOTAL}', '{$inv['odate']}', 'Hire Invoice no H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record.");
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2))\r\n\t\t\tWHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $stkacc = qryAccountsName("Hire Sales");
    $stkacc = $stkacc["accid"];
    # Make ledger record
    custledger($inv["cusnum"], $stkacc, $inv["odate"], $inv["invid"], "Hire Invoice No. H{$real_invid}", $TOTAL, "d");
    custDT($TOTAL, $inv["cusnum"], $inv["odate"]);
    // ------------------------------------------------------------------------
    # Get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_nons_inv_items\r\n\t\t\tWHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    $item_count = pg_num_rows($item_rslt);
    $totamt = 0;
    while ($item_data = pg_fetch_array($item_rslt)) {
        $totamt += $item_data["amt"];
        $sql = "SELECT * FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $discount = $item_data["amt"] / 100 * $traddisc;
        // Add up revenue
        $sql = "INSERT INTO hire.revenue (group_id, asset_id, total, discount,\r\n\t\t\t\t\thire_invnum, inv_invnum, cusname)\r\n\t\t\t\tVALUES ('{$asset_data['grpid']}', '{$item_data['asset_id']}',\r\n\t\t\t\t\t'{$item_data['amt']}', '{$discount}', '{$hirenum}',\r\n\t\t\t\t\t'{$real_invid}', '{$inv['cusname']}')";
        db_exec($sql) or errDie("Unable to update revenue");
        $sql = "INSERT INTO cubit.nons_inv_items (invid, qty, description,\r\n\t\t\tdiv, amt, unitcost, vatex, accid, asset_id)\r\n\t\tVALUES ('{$invid}', '{$item_data['qty']}',\r\n\t\t\t'{$item_data['description']}', '{$item_data['div']}', '{$item_data['amt']}',\r\n\t\t\t'{$item_data['amt']}',  '2', '{$item_data['accid']}', '{$item_data['asset_id']}')";
        db_exec($sql) or errDie("Unable to add non stock items.");
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP,\r\n\t\t\t\t\tinv_invnum='{$real_invid}', value='{$item_data['amt']}'\r\n\t\t\t\tWHERE item_id='{$item_data['item_id']}'";
        db_exec($sql) or errDie("Unable to record asset return time.");
    }
    // Add the delivery discount to the total revenue
    if ($inv["delivery"]) {
        $discount = $inv["delivery"] / 100 * $traddisc;
        $sql = "INSERT INTO hire.revenue (discount)\r\n\t\t\t\tVALUES ('{$discount}')";
        db_exec($sql) or errDie("Unable to update revenue");
    }
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $sql = "UPDATE hire.hire_invoices SET done='y', delivery='0.00'\r\n\t\t\tWHERE invnum='" . getHirenum($inv["hire_invid"]) . "'";
    db_exec($sql) or errDie("Unable to update invoices.");
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $TOTAL, $inv["vat"]);
    $details = "";
    $SUBTOT = sprint($totamt);
    for ($i = 0; $i <= $page; $i++) {
        if ($monthly) {
            $monthly_out = "\r\n\t\t\t<tr>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>Invoiced to date " . date("d-m-Y") . "</td>\r\n\t\t\t</tr>";
        } else {
            $monthly_out = "";
        }
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$real_invid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Hire No:</b> {$hirenum}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cus['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cus["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>No of Days</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Rate</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Delivery</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['delivery']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Discount</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['discount']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$monthly_out}\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    $amt = $pcash + $pcheque + $pcc;
    $_POST["amt"] = $amt;
    $_POST["date"] = $inv["odate"];
    recvpayment_write();
    $sql = "UPDATE cubit.nons_invoices SET cash='{$pcash}' WHERE invid='{$inv['invid']}'";
    db_exec($sql) or errDie("Unable to update cash value.");
    pglib_transaction("COMMIT");
    // Retrieve the template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');</script>\r\n\t\t\t{$details}";
        require "../tmpl-print.php";
    } else {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\tmove (\"../{$template}?invid={$inv['invid']}&type=nons\");\r\n\t\t</script>";
        require "template.php";
    }
}
Example #16
0
/** 1.0-rc1 */
function upgradefmSQLPass_01009($__FM_CONFIG, $running_version)
{
    global $fmdb, $module_name;
    $success = version_compare($running_version, '1.0-beta8', '<') ? upgradefmSQLPass_01008($__FM_CONFIG, $running_version) : true;
    if (!$success) {
        return false;
    }
    $fm_user_caps = getOption('fm_user_caps');
    /** Update user capabilities */
    $fm_user_caps['fmSQLPass'] = array('view_all' => 'View All', 'manage_servers' => 'Server Management', 'manage_passwords' => 'Password Management', 'manage_settings' => 'Manage Settings');
    if (!setOption('fm_user_caps', $fm_user_caps)) {
        return false;
    }
    $fmdb->get_results("SELECT * FROM `fm_users`");
    if ($fmdb->num_rows) {
        $count = $fmdb->num_rows;
        $result = $fmdb->last_result;
        for ($i = 0; $i < $count; $i++) {
            $user_caps = null;
            /** Update user capabilities */
            $temp_caps = null;
            foreach ($fm_user_caps['fmSQLPass'] as $slug => $trash) {
                $user_caps = isSerialized($result[$i]->user_caps) ? unserialize($result[$i]->user_caps) : $result[$i]->user_caps;
                if (@array_key_exists('fmSQLPass', $user_caps)) {
                    if (array_key_exists('read_only', $user_caps['fmSQLPass'])) {
                        $temp_caps['fmSQLPass']['view_all'] = 1;
                        unset($user_caps['fmSQLPass']['read_only']);
                    }
                }
            }
            if (@array_key_exists('fmSQLPass', $temp_caps)) {
                $user_caps['fmSQLPass'] = array_merge($temp_caps['fmSQLPass'], $user_caps['fmSQLPass']);
            }
            $fmdb->query("UPDATE fm_users SET user_caps = '" . serialize($user_caps) . "' WHERE user_id=" . $result[$i]->user_id);
            if (!$fmdb->result) {
                return false;
            }
        }
    }
    setOption('version', '1.0-rc1', 'auto', false, 0, $module_name);
    return true;
}
function sticky_pre_populate_the_form($form)
{
    if ($form['isSticky']) {
        $current_page = GFFormDisplay::get_current_page($form["id"]);
        if ($current_page == 1) {
            global $valid;
            // Get the stored entry ID
            $entry_id = sticky_getEntryOptionKeyForGF($form);
            // If the form has been submited, is valid and we are not in the preview area
            if ($valid && strpos($_SERVER['REQUEST_URI'], 'preview') == false) {
                // We have a previously saved entry
                if (get_option($entry_id)) {
                    // Get the entry
                    $form_fields = RGFormsModel::get_lead(get_option($entry_id));
                    // If an entry is found we need prepare if for insertion into the form
                    if ($form_fields && $form_fields["status"] != "trash") {
                        // Create new correctly formated keys and get rid of the old ones
                        foreach ($form_fields as $key => &$value) {
                            // If the key is numeric we need to change it from [X.X] to [input_X_X]
                            if (is_numeric($key)) {
                                $new_key = str_replace(".", "_", "input_{$key}");
                                $form_fields[$new_key] = $form_fields[$key];
                                unset($form_fields[$key]);
                                if (isSerialized($value)) {
                                    $dump = unserialize($value);
                                    foreach ($dump as $k => &$v) {
                                        if (is_array($v)) {
                                            unset($form_fields[$new_key]);
                                            foreach ($v as $k2 => &$v2) {
                                                $a[] = $v2;
                                            }
                                            $form_fields[$new_key] = $a;
                                        }
                                    }
                                    unset($a);
                                }
                                // If we have an upload field
                                if (strpos($value, "uploads/")) {
                                    $upload = $value;
                                }
                            }
                        }
                        // Add is_submit_id field
                        $form_id = $form['id'];
                        $form_fields["is_submit_{$form_id}"] = "1";
                        $_POST = $form_fields;
                        // If no entry is found; unset the stored entry ID
                    } else {
                        update_option($entry_id, "");
                    }
                }
            }
        }
    }
    // Replace {upload} with reference to uploaded file
    if (isset($upload)) {
        foreach ($form["fields"] as &$field) {
            foreach ($field as $key => &$value) {
                if ($key == "content") {
                    $value = str_replace("{upload}", $upload, $value);
                }
            }
        }
    }
    return $form;
}
Example #18
0
/**
 * Returns an option value
 *
 * @since 1.0
 * @package facileManager
 * @subpackage fmSQLPass
 */
function getServerCredentials($account_id = 0, $server_serial_no)
{
    global $fmdb, $__FM_CONFIG;
    $query = "SELECT * FROM fm_{$__FM_CONFIG['fmSQLPass']['prefix']}servers WHERE server_serial_no={$server_serial_no} AND account_id={$account_id}";
    $fmdb->get_results($query);
    if ($fmdb->num_rows) {
        $results = $fmdb->last_result;
        if (isSerialized($results[0]->server_credentials)) {
            return unserialize($results[0]->server_credentials);
        }
        return $results[0]->server_credentials;
    }
    return false;
}
function confirm()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($asset_id, "num", 1, 9, "Invalid asset selection.");
    $v->isOk($cust_id, "num", 1, 9, "Invalid customer selection.");
    $v->isOk($from_year, "num", 4, 4, "Invalid from date (year).");
    $v->isOk($from_month, "num", 1, 2, "Invalid from date (month).");
    $v->isOk($from_day, "num", 1, 2, "Invalid from date (day).");
    $v->isOk($to_year, "num", 4, 4, "Invalid to date (year).");
    $v->isOk($to_month, "num", 1, 2, "Invalid to date (month).");
    $v->isOk($to_day, "num", 1, 2, "Invalid to date (day).");
    $e_from = getDTEpoch("{$from_year}-{$from_month}-{$from_day} 0:00:00");
    $e_to = getDTEpoch("{$to_year}-{$to_month}-{$to_day} 23:59:59");
    for ($i = $e_from; $i < $e_to; $i += DAYS) {
        if (isHired($asset_id, date("Y-m-d", $i))) {
            $v->addError(0, "Asset is hired out on " . date("d-m-Y", $i) . ".");
        }
    }
    if (!$asset_id) {
        $v->addError(0, "Please select an asset first.");
    }
    if (!$cust_id) {
        $v->addError(0, "Please select a customer first.");
    }
    if ($v->isError()) {
        return enter($v->genErrors());
    }
    // Booking Date
    $from_date = "{$from_day}-{$from_month}-{$from_year}";
    $from_date_db = dateFmt($from_year, $from_month, $from_day);
    $to_date = "{$to_day}-{$to_month}-{$to_year}";
    $to_date_db = dateFmt($to_year, $to_month, $to_day);
    if (!isset($units)) {
        $units = 1;
    }
    $sql = "SELECT * FROM hire.bookings\r\n\t\t\tWHERE asset_id='{$asset_id}' AND\r\n\t\t\t\t('{$from_date_db}' BETWEEN from_date AND to_date OR\r\n\t\t\t\t '{$to_date_db}' BETWEEN from_date AND to_date)";
    $bk_rslt = db_exec($sql) or errDie("Unable to retrieve bookings.");
    if (pg_num_rows($bk_rslt) && isSerialized($asset_id)) {
        return enter("<li class='err'>Item has already been booked in the\r\n\t\t\tspecified date range</li>");
    }
    // Retrieve the asset description
    $sql = "SELECT * FROM cubit.assets WHERE id='{$asset_id}'";
    $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
    $asset_data = pg_fetch_array($asset_rslt);
    $asset_name = getSerial($asset_data["id"], 1) . " " . $asset_data["des"];
    // Retrieve the customer name
    $sql = "SELECT surname FROM cubit.customers WHERE cusnum='{$cust_id}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_name = pg_fetch_result($cust_rslt, 0);
    if (!isSerialized($asset_id)) {
        $units_input = "<input type='text' name='units' value='{$units}' size='2' />";
    } else {
        $units_input = "1";
    }
    $OUTPUT = "<h3>" . ucfirst($page_option) . " Booking</h3>\r\n\t<form method='post' action='" . SELF . "'>\r\n\t<input type='hidden' name='key' value='write' />\r\n\t<input type='hidden' name='page_option' value='{$page_option}' />\r\n\t<input type='hidden' name='id' value='{$id}' />\r\n\t<input type='hidden' name='asset_id' value='{$asset_id}' />\r\n\t<input type='hidden' name='cust_id' value='{$cust_id}' />\r\n\t<input type='hidden' name='from_year' value='{$from_year}' />\r\n\t<input type='hidden' name='from_month' value='{$from_month}' />\r\n\t<input type='hidden' name='from_day' value='{$from_day}' />\r\n\t<input type='hidden' name='to_year' value='{$to_year}' />\r\n\t<input type='hidden' name='to_month' value='{$to_month}' />\r\n\t<input type='hidden' name='to_day' value='{$to_day}' />\r\n\t<input type='hidden' name='units' value='1' />\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='2'>Confirm</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Small Plant</td>\r\n\t\t\t<td>{$asset_name}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Customer</td>\r\n\t\t\t<td>{$cust_name}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Units</td>\r\n\t\t\t<td>{$units_input}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Booking Date</td>\r\n\t\t\t<td>{$from_date} &nbsp; <b>To</b> &nbsp; {$to_date}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td><input type='submit' name='key' value='&laquo Correction' /></td>\r\n\t\t\t<td align='right'><input type='submit' value='Write &raquo ' /></td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>";
    return $OUTPUT;
}
function update($_POST)
{
    extract($_POST);
    $collect_ar = array();
    if (!empty($client_collect)) {
        $collect_ar[] = "Client Collect";
    }
    if (!empty($collect)) {
        $collect_ar[] = "Collect";
    }
    if (!empty($deliver)) {
        $collect_ar[] = "Deliver";
    }
    $collection = implode(", ", $collect_ar);
    // 	if ((in_array("Collect", $collect_ar) && in_array("Client Collect", $collect_ar))
    // 		|| (count($collect_ar) == 3)) {
    // 		return "<li class='err'>Invalid collection options selected.</li>";
    // 	}
    if (count($collect_ar) > 1 && in_array("Client Collect", $collect_ar)) {
        return "<li class='err'>Invalid collection options selected.</li>";
    }
    $temp_assets = explode(",", $temp_assets);
    pglib_transaction("BEGIN");
    // Stock Sales
    if (isset($snremove) && is_array($snremove)) {
        foreach ($snremove as $id => $value) {
            $sql = "DELETE FROM hire.hire_stock_items WHERE id='{$id}'";
            db_exec($sql) or errDie("Unable to remove stock item.");
        }
    }
    if (isset($snstock) && $snstock > 0) {
        if (!is_numeric($snqty)) {
            $snqty = 1;
        }
        #get vatperc for this item
        $get_vatp = "SELECT vat_amount FROM vatcodes WHERE id = '{$snvatcode}' LIMIT 1";
        $run_vatp = db_exec($get_vatp) or errDie("Unable to get vat code information.");
        if (pg_numrows($run_vatp) < 1) {
            $vatperc = 0;
        } else {
            $vatperc = pg_fetch_result($run_vatp, 0, 0);
        }
        //		$sql = "SELECT selamt FROM cubit.stock WHERE stkid='$snstock'";
        //		$price_rslt = db_exec($sql) or errDie("Unable to retrieve price.");
        //		$price = pg_fetch_result($price_rslt, 0);
        $price = get_excl_stock($snstock) * $snqty;
        $excl_price = get_excl_stock($snstock) * $snqty;
        $vatamount = sprint($excl_price / 100 * $vatperc);
        $price += 0;
        $price += sprint($excl_price / 100 * $vatperc);
        $snamt = $price * $snqty;
        #hack, because stores functionality isnt working ...
        $get_store = "SELECT whid FROM stock WHERE stkid = '{$snstock}' LIMIT 1";
        $run_store = db_exec($get_store) or errDie("Unable to get stock store information.");
        $snstore = pg_fetch_result($run_store, 0, 0);
        $sql = "\r\n\t\t\tINSERT INTO hire.hire_stock_items (\r\n\t\t\t\twhid, invid, stkid, qty, vatcode, unitcost, \r\n\t\t\t\tamount, excl_amount, vatamount\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$snstore}', '{$invid}', '{$snstock}', '{$snqty}', '{$snvatcode}', '" . sprint($price / $snqty) . "', \r\n\t\t\t\t'" . sprint($snamt / $snqty) . "', '{$excl_price}', '{$vatamount}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add stock.");
        $sql = "UPDATE cubit.stock SET alloc=(alloc+'{$snqty}') WHERE stkid='{$snstock}'";
        db_exec($sql) or errDie("Unable to update stock allocation.");
    }
    if (isset($nhalf_day) && $nhalf_day == "checked") {
        $nhalf_day = 1;
    } else {
        $nhalf_day = 0;
    }
    if (isset($nweekends) && $nweekends == "checked") {
        $nweekends = 1;
    } else {
        $nweekends = 0;
    }
    $sql = "UPDATE hire.hire_invoices SET comm='{$comm}' WHERE invid='{$invid}'";
    $comm_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    foreach ($temp_assets as $key => $value) {
        $sql = "SELECT * FROM cubit.assets WHERE id='{$key}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
    }
    if (isset($amount)) {
        foreach ($amount as $key => $value) {
            // 			if (empty($monthly)) {
            // 				$amount[$key] = "";
            // 			}
            #redundant code ... breaks new hire if you click update multiple times (sets item amount = 0 after second update)
            //			if (!user_is_admin(USER_ID)) {
            //				$amount[$key] = "";
            //			}
            if (!isset($half_day[$key]) || empty($half_day[$key])) {
                $half_day[$key] = 0;
            }
            if (!isset($weekends[$key]) || empty($weekends[$key])) {
                $weekends[$key] = 0;
            } else {
                $weekends[$key] = 1;
            }
            if (!isset($total_days[$key]) || empty($total_days[$key])) {
                $epoch_from = strtotime($from_date[$key]);
                $epoch_to = strtotime($to_date[$key]);
                $total_days[$key] = ($epoch_to - $epoch_from) / (60 * 60 * 24) + 1;
                $total_days[$key] = ceil($total_days[$key]);
            }
            $sql = "SELECT qty, total_days, half_day FROM hire.hire_invitems WHERE id='{$key}'";
            $old_rslt = db_exec($sql) or errDie("Unable to retrieve old qty.");
            list($oldqty, $olddays, $oldhalf_day) = pg_fetch_array($old_rslt);
            if (!isset($oldqty)) {
                $oldqty = 1;
            }
            if (!isset($qty[$key])) {
                $oldqty = 1;
                $qty[$key] = 1;
            }
            if ($half_day[$key]) {
                $half_day[$key] = 1;
                $recalc = FALSE;
            } else {
                $half_day[$key] = 0;
            }
            if (empty($amount) && $amount != 0 || $oldqty != $qty[$key] || $olddays != $total_days[$key] || (!isset($amount[$key]) or empty($amount[$key])) || $half_day == 1) {
                if ($basis[$key] == "per_day") {
                    $to_time = strtotime($from_date[$key]) + $total_days[$key] * (60 * 60 * 24);
                    $hifrm = "{$mfrm_year[$key]}-{$mfrm_month[$key]}-{$mfrm_day[$key]}";
                    $hito = date("Y-m-d", $to_time);
                    $hours = "0";
                    /* calculate amount */
                    $ftime = getDTEpoch("{$hifrm} 0:00:00");
                    $ttime = getDTEpoch("{$hito} 0:00:00");
                    $days = 0;
                    $weeks = 0;
                    $months = 0;
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $total_days[$key];
                } else {
                    if ($basis[$key] == "per_hour") {
                        $hifrm = $hito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $hours;
                        $weeks = 0;
                        $months = 0;
                        if (empty($hours) || !is_numeric($hours)) {
                            return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                        }
                    } else {
                        if ($nbasis == "per_week") {
                            $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                            $timeunits = $weeks;
                            $hours = 0;
                            $months = 0;
                            if (empty($weeks) || !is_numeric($weeks)) {
                                return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                            }
                        } else {
                            if ($nbasis == "per_month") {
                                $nhifrm = $nhito = mkDate($pinv_year, $pinv_month, $pinv_day);
                                $timeunits = $months;
                                $weeks = 0;
                                $hours = 0;
                                if (empty($months) || !is_numeric($months)) {
                                    return "<li class='err'><b>ERROR</b>: Invalid amount of months.</li>";
                                }
                            }
                        }
                    }
                }
                if ($half_day[$key]) {
                    //					$amount[$key] = ($qty[$key] * $timeunits * (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) - (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) + ((basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key])) / halfday_rate());
                    $amount[$key] = sprint($qty[$key] * ($timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]) - basisPrice($cusnum, $asset_id[$key], $basis[$key]) + basisPrice($cusnum, $asset_id[$key], $basis[$key]) / halfday_rate()));
                } else {
                    $amount[$key] = $qty[$key] * $timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]);
                }
            }
            if ($amount[$key] == 0) {
                $amount[$key] = 0;
                $blank_amount = 1;
            } else {
                $blank_amount = 0;
            }
            $sql = "\r\n\t\t\t\tUPDATE hire.hire_invitems \r\n\t\t\t\tSET amt='{$amount[$key]}', half_day='{$half_day[$key]}', weekends='{$weekends[$key]}', \r\n\t\t\t\t\ttotal_days='{$total_days[$key]}', qty='{$qty[$key]}' \r\n\t\t\t\tWHERE id='{$key}'";
            db_exec($sql) or errDie("Unable to update item amount.");
            $sql = "\r\n\t\t\t\tUPDATE hire.reprint_invitems \r\n\t\t\t\tSET amt='{$amount[$key]}', half_day='{$half_day[$key]}', weekends='{$weekends[$key]}' \r\n\t\t\t\tWHERE item_id='{$key}'";
            db_exec($sql) or errDie("Unable to update return item amount.");
            if ($blank_amount) {
                $amount[$key] = "";
            }
            //$hifrm = "$hifrm_year[$key]-$hifrm_month[$key]-$hifrm_day[$key]";
            //$hito = "$hito_year[$key]-$hito_month[$key]-$hito_day[$key]";
            if (!isset($remove[$key])) {
                $sql = "SELECT basis FROM hire.hire_invitems WHERE id='{$key}'";
                $item_rslt = db_exec($sql) or errDie("Unable to retrieve basis.");
                $mbasis = pg_fetch_result($item_rslt, 0);
                /* determine time units */
                if ($mbasis == "per_day") {
                    $mfrm = mkdate($mfrm_year[$key], $mfrm_month[$key], $mfrm_day[$key]);
                    $mto = mkdate($mto_year[$key], $mto_month[$key], $mto_day[$key]);
                    /* calculate amount */
                    $ftime = mktime(0, 0, 0, $mfrm_month[$key], $mfrm_day[$key], $mfrm_year[$key]);
                    $ttime = mktime(0, 0, 0, $mto_month[$key], $mto_day[$key], $mto_year[$key]);
                    $days = 0;
                    if (empty($weeks)) {
                        $weeks = 0;
                    }
                    if (empty($hours)) {
                        $hours = 0;
                    }
                    if (empty($months)) {
                        $months = 0;
                    }
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $days;
                    $sql = "\r\n\t\t\t\t\t\tUPDATE hire.hire_invitems \r\n\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}' \r\n\t\t\t\t\t\tWHERE id='{$key}'";
                    db_exec($sql) or errDie("Unable to update items.");
                    $sql = "\r\n\t\t\t\t\t\tUPDATE hire.reprint_invitems \r\n\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}' \r\n\t\t\t\t\t\tWHERE item_id='{$key}'";
                    db_exec($sql) or errDie("Unable to update reprint items.");
                }
            } else {
                // Delete the old items
                $sql = "DELETE FROM hire.hire_invitems WHERE id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old items.");
                $sql = "DELETE FROM hire.reprint_invitems WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old reprint items.");
                //.Remove if the item has been hired as well
                $sql = "DELETE FROM hire.assets_hired WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove items from hired log.");
            }
        }
    }
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $invb = pg_fetch_array($hi_rslt);
    // Default basis
    if (!empty($nasset_id) && $nbasis == "0") {
        list($serialqty, $tasset_id) = explode(":", $nasset_id);
        $nbasis = default_basis($tasset_id);
    }
    // Insert new items
    if ($nasset_id != "0") {
        if ($nasset_id == "0") {
            return "<li class='err'><b>ERROR</b>: No asset selected.</li>";
        }
        /* get asset id */
        list($serialqty, $nasset_id) = explode(":", $nasset_id);
        /* disabled items don't get passed through */
        if ($serialqty == "s" || !isset($nqty)) {
            $nqty = "1";
        } else {
            $sql = "SELECT serial2 FROM cubit.assets WHERE id='{$nasset_id}'";
            $dqty_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $dqty = pg_fetch_result($dqty_rslt, 0);
            if ($dqty - $nqty < 0) {
                return "<li class='err'><b>ERROR</b>: Invalid quantity. Only &nbsp; <b>{$dqty}</b> &nbsp; available.</li>";
            }
        }
        if (empty($nqty) || !is_numeric($nqty)) {
            return "<li class='err'><b>ERROR</b>: Invalid quantity</li>";
        }
        // Default basis
        if ($nbasis == "0") {
            $nbasis = default_basis($nasset_id);
        }
        /* determine time units */
        if ($nbasis == "per_day") {
            $nhifrm = mkdate($nhifrm_year, $nhifrm_month, $nhifrm_day);
            $nhito = mkdate($nhito_year, $nhito_month, $nhito_day);
            $hours = "0";
            /* calculate amount */
            $ftime = mktime(0, 0, 0, $nhifrm_month, $nhifrm_day, $nhifrm_year);
            $ttime = mktime(0, 0, 0, $nhito_month, $nhito_day, $nhito_year);
            $days = 0;
            $weeks = 0;
            $months = 0;
            while ($ftime <= $ttime) {
                if (date("w", $ftime) == 0 && isset($nweekends) && $nweekends) {
                    $days += 0.6;
                } else {
                    ++$days;
                }
                $ftime += 24 * 60 * 60;
            }
            $timeunits = $days;
        } else {
            if ($nbasis == "per_hour") {
                $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                $timeunits = $hours;
                $weeks = 0;
                $months = 0;
                if (empty($hours) || !is_numeric($hours)) {
                    return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                }
            } else {
                if ($nbasis == "per_week") {
                    $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                    $timeunits = $weeks;
                    $hours = 0;
                    $months = 0;
                    if (empty($weeks) || !is_numeric($weeks)) {
                        return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                    }
                } else {
                    if ($nbasis == "per_month") {
                        $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $months;
                        $hours = 0;
                        $weeks = 0;
                        if (empty($months) || !is_numeric($months)) {
                            return "<li class='err'><b>ERROR</b>: Invalid amount of months.</li>";
                        }
                    } else {
                        return "<li class='err'><b>ERROR</b>: No basis selected.</li>";
                    }
                }
            }
        }
        /* calculate amount according to hire settings, quantity and time units */
        if ($nhalf_day) {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis) - basisPrice($cusnum, $nasset_id, $nbasis) + basisPrice($cusnum, $nasset_id, $nbasis) / halfday_rate();
        } else {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis);
        }
        /* insert item */
        $sql = "SELECT asset_id FROM hire.hire_invitems\r\n\t\t\t\tWHERE invid='{$invid}' AND asset_id='{$nasset_id}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        // No duplicate assets
        if (!pg_num_rows($asset_rslt) || !isSerialized($nasset_id)) {
            if (isHired($nasset_id)) {
                return "\r\n\t\t\t\t<li class='err'>\r\n\t\t\t\t\t<b>ERROR</b>: Asset has already hired out.\r\n\t\t\t\t</li>";
            }
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tmonths, collection, half_day, weekends\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$months}', '{$collection}', '{$nhalf_day}', '{$nweekends}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create new invoice item.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\r\n\t\t\t\tINSERT INTO hire.reprint_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tmonths, collection, half_day, weekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$months}', '{$collection}', '{$nhalf_day}', '{$nweekends}', '{$item_id}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create reprint invoice item.");
        }
    }
    if ($monthly == "true") {
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
    } else {
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
        $mii_rslt = db_exec($sql) or errDie("Unable to retrieve inv items.");
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
        while ($item = pg_fetch_array($mii_rslt)) {
            $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, \r\n\t\t\t\t\tbasis, hours, weeks, months, collection, half_day, \r\n\t\t\t\t\tweekends, item_id, invnum\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$item['invid']}', '{$item['asset_id']}', '{$item['qty']}', '{$item['amt']}', '{$item['from_date']}', '{$item['to_date']}', \r\n\t\t\t\t\t'{$item['basis']}', '{$item['hours']}', '{$item['weeks']}', '{$item['months']}', '{$item['collection']}', '{$item['half_day']}',\r\n\t\t\t\t\t'{$item['weekends']}', '{$item['id']}', '{$invb['invnum']}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create monthly items.");
        }
    }
    $sql = "SELECT * FROM hire.reprint_invoices WHERE invid='{$invid}'";
    $ri_rslt = db_exec($sql) or errDie("Unable to retrieve reprints.");
    // Create a new entry, or update
    if (pg_num_rows($ri_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.reprint_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}',\r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$delchrg}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}' \r\n\t\t\tWHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to update reprint.");
    } else {
        $sql = "\r\n\t\t\tINSERT INTO hire.reprint_invoices (\r\n\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, ordno, \r\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, \r\n\t\t\t\tsubtot, vat, total, balance, comm, printed, done, div, \r\n\t\t\t\tusername, rounding, delvat, vatnum, pcash, pcheque, \r\n\t\t\t\tpcc, pcredit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}',\r\n\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', \r\n\t\t\t\t'{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', \r\n\t\t\t\t'" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', \r\n\t\t\t\t'{$invb['pcc']}', '{$invb['pcredit']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add reprint.");
    }
    $sql = "SELECT * FROM hire.monthly_invoices WHERE invid='{$invid}' OR invnum='{$invb['invnum']}' AND invnum!=0";
    $mi_rslt = db_exec($sql) or errDie("Unable to retrieve monthly.");
    // Should we create a new entry
    if (pg_num_rows($mi_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.monthly_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}', \r\n\t\t\t\thire_invid='{$invid}' \r\n\t\t\tWHERE invid='{$invb['invid']}'";
    } elseif (empty($monthly)) {
        $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invoices (\r\n\t\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, \r\n\t\t\t\t\tordno, chrgvat, terms, traddisc, salespn, \r\n\t\t\t\t\todate, delchrg, subtot, vat, total, balance, \r\n\t\t\t\t\tcomm, printed, done, div, username, rounding, delvat, \r\n\t\t\t\t\tvatnum, pcash, pcheque, pcc, pcredit, invoiced_month, \r\n\t\t\t\t\thire_invid\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', \r\n\t\t\t\t\t'{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', \r\n\t\t\t\t\t'{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}', '{$invb['total']}', '{$invb['balance']}', \r\n\t\t\t\t\t'{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', '" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', \r\n\t\t\t\t\t'{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', '{$invb['pcc']}', '{$invb['pcredit']}', '" . date("m") . "', \r\n\t\t\t\t\t'{$invb['invid']}' \r\n\t\t\t\t)";
    }
    db_exec($sql) or errDie("Unable to store monthly invoice.");
    pglib_transaction("COMMIT");
    if (!isSerialized($nasset_id) && (!isset($_SESSION["ns"]) || !$_SESSION["ns"])) {
        $_SESSION["ns"] = 1;
    } else {
        $_SESSION["ns"] = 0;
    }
    if (isset($upBtn)) {
        if ($upBtn == "Return") {
            return returnHire();
        } elseif ($upBtn == "Invoice") {
            return invoiceHire();
        }
    }
    return false;
}
Example #21
0
    /**
     * Displays the form to add new server
     */
    function printForm($data = '', $action = 'add')
    {
        global $fmdb, $__FM_CONFIG;
        $server_id = 0;
        $server_name = $server_groups = $server_type = $server_port = null;
        $server_cred_user = $server_cred_password = $server_credentials = null;
        $server_type = 'database';
        $ucaction = ucfirst($action);
        /** Build groups options */
        basicGetList('fm_' . $__FM_CONFIG['fmSQLPass']['prefix'] . 'groups', 'group_name', 'group_');
        $group_options = null;
        $group_count = $fmdb->num_rows;
        $group_results = $fmdb->last_result;
        for ($i = 0; $i < $group_count; $i++) {
            $group_options[$i][] = $group_results[$i]->group_name;
            $group_options[$i][] = $group_results[$i]->group_id;
        }
        if (!empty($_POST) && !array_key_exists('is_ajax', $_POST)) {
            if (is_array($data)) {
                extract($data);
            }
        } elseif (@is_object($data[0])) {
            extract(get_object_vars($data[0]));
        }
        /** Check name field length */
        $server_name_length = getColumnLength('fm_' . $__FM_CONFIG['fmSQLPass']['prefix'] . 'servers', 'server_name');
        $server_types = buildSelect('server_type', 'server_type', $this->getServerTypes(), $server_type);
        $groups = is_array($group_options) ? buildSelect('server_groups', 1, $group_options, $server_groups, 4, null, true) : __('Server Groups need to be defined first.');
        /** Handle credentials */
        if (isSerialized($server_credentials)) {
            $server_credentials = unserialize($server_credentials);
            list($server_cred_user, $server_cred_password) = $server_credentials;
            unset($server_credentials);
        }
        $popup_title = $action == 'add' ? __('Add Server') : __('Edit Server');
        $popup_header = buildPopup('header', $popup_title);
        $popup_footer = buildPopup('footer');
        $return_form = sprintf('<form name="manage" id="manage" method="post" action="">
		%s
			<input type="hidden" name="action" id="action" value="%s" />
			<input type="hidden" name="server_type" id="server_type" value="%s" />
			<input type="hidden" name="server_id" id="server_id" value="%d" />
			<table class="form-table">
				<tr>
					<th width="33&#37;" scope="row"><label for="server_name">%s</label></th>
					<td width="67&#37;"><input name="server_name" id="server_name" type="text" value="%s" size="40" maxlength="%s" /></td>
				</tr>
				<tr>
					<th width="33&#37;" scope="row"><label for="server_type">%s</label></th>
					<td width="67&#37;">%s</td>
				</tr>
				<tr>
					<th width="33&#37;" scope="row"><label for="server_port">%s</label></th>
					<td width="67&#37;"><input type="number" name="server_port" value="%d" placeholder="3306" onkeydown="return validateNumber(event)" maxlength="5" max="65535" /></td>
				</tr>
				<tr>
					<th width="33&#37;" scope="row"><label for="server_groups">%s</label></th>
					<td width="67&#37;">%s</td>
				</tr>
				<tr>
					<th width="33&#37;" scope="row"><label for="server_cred_user">%s</label></th>
					<td width="67&#37;"><input name="server_credentials[]" id="server_cred_user" type="text" value="%s" size="40" /></td>
				</tr>
				<tr>
					<th width="33&#37;" scope="row"><label for="server_cred_password">%s</label></th>
					<td width="67&#37;"><input name="server_credentials[]" id="server_cred_password" type="password" value="%s" size="40" /></td>
				</tr>
			</table>
		%s
		</form>
		<script>
			$(document).ready(function() {
				$("#manage select").select2({
					width: "200px",
					minimumResultsForSearch: 10
				});
			});
		</script>', $popup_header, $action, $server_type, $server_id, __('Hostname'), $server_name, $server_name_length, __('Server Type'), $server_types, __('Server Port'), $server_port, __('Groups'), $groups, __('Username'), $server_cred_user, __('Password'), $server_cred_password, $popup_footer);
        return $return_form;
    }
function details($_GET)
{
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid = '{$invid}'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found[1]</i>";
    }
    $inv = pg_fetch_array($invRslt);
    // Cash deposit
    if ($inv["deposit_type"] == "CSH" && $inv["deposit_amt"] > 0) {
        $get_ar = array();
        foreach ($_GET as $key => $value) {
            if ($key != "key") {
                $get_ar[] = "{$key}={$value}";
            }
        }
        $get_vars = implode("&", $get_ar);
        $deposit_receipt = "<script>\r\n\t\t\t\t\t\t\t\tprinter(\"" . SELF . "?key=deposit{$get_vars}\")\r\n\t\t\t\t\t\t\t</script>";
    } else {
        $deposit_receipt = "";
    }
    if ($inv['rounding'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    $td = $inv['odate'];
    db_conn('cubit');
    $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid = '{$inv['invid']}'";
    $crslt = db_exec($sql);
    if ($inv['terms'] == 1) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
    }
    $change = sprint(sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) - sprint($inv['total'] - $inv['rounding']));
    $inv['pcash'] = sprint($inv['pcash'] - $change);
    if ($inv['pcash'] < 0) {
        $inv['pcash'] = 0;
    }
    if (sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) != sprint($inv['total'] - $inv['rounding'])) {
        return "<li class=err>The total of all the payments is not equal to the invoice total.<br>\r\n\t\tPlease edit the invoice and try again(You can only overpay with cash)</li>";
    }
    db_connect();
    pglib_transaction("BEGIN");
    $invnum = getHirenum($invid, 1);
    $sql = "UPDATE hire.reprint_invoices SET invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to assign hire invoice number.");
    $Sl = "INSERT INTO ncsrec (oldnum,newnum, div) VALUES ('{$invid}','{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    //unlock(2);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found[2]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $commision = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM assets WHERE id = '{$stkd['asset_id']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_connect();
            //this was set to the stock vatcode ??? must be the pur_item code ...
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "<li class='err'>Please select the vatcode for all your stock.</li>";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td>{$stk['stkcod']}</td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stk["selamt"]) . "</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            //$commision=$commision+coms($inv['salespn'], $stkd['amt'], $stk['com']);
            # Put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td></td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stkd['description']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stkd["unitcost"]) . "</td>\r\n\t\t\t\t<td>{$stkd['disc']}</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    $nt = sprint($inv['pcredit']);
    $sd = date("Y-m-d");
    $ro = $inv['rounding'];
    $ro += 0;
    com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    $nsp = 0;
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    db_conn('cubit');
    if ($inv['cusnum'] > 0 && $nt > 0) {
        # Record the payment on the statement
        $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $nt, "d");
        recordDT($nt, $inv['cusnum'], $inv['odate']);
        db_conn('cubit');
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','{$nt}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['terms'] == 1) {
        $Sl = "INSERT INTO crec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    } else {
        $Sl = "INSERT INTO posrec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    }
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}','{$inv['cusname']}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    $refnum = getrefnum();
    $fcash = $inv['pcash'];
    $fccp = $inv['pcc'];
    $fcheque = $inv['pcheque'];
    $fcredit = $inv['pcredit'];
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE hire.hire_invoices SET pchange='{$change}',printed = 'y', done ='y',invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('0','{$invnum}','{$inv['delivery']}','{$disc}', '{$inv['odate']}', '{$inv['delivery']}', '" . USER_DIV . "',({$SUBTOT}+{$inv['delivery']}))";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    if (strlen($inv['comm']) > 0) {
        $Com = "<table><tr><td>" . nl2br($inv['comm']) . "</td></tr></table>";
    } else {
        $Com = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$date}', 'POS Invoice No.{$invnum}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "<center>\r\n\t{$deposit_receipt} {$cc}\r\n\t<h2>Tax Invoice</h2>\r\n\t<table cellpadding='0' cellspacing='1' border=0 width=750>\r\n\t<tr><td valign=top width=40%>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\r\n\t\t\t<tr><td>{$inv['surname']}</td></tr>\r\n\t\t</table>\r\n\t</td><td valign=top width=35%>\r\n\t\t" . COMP_NAME . "<br>\r\n\t\t" . COMP_ADDRESS . "<br>\r\n\t\t" . COMP_TEL . "<br>\r\n\t\t" . COMP_FAX . "<br>\r\n\t\tReg No. " . COMP_REGNO . "<br>\r\n\t</td><td valign=bottom align=right width=25%>\r\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\r\n\t\t\t<tr><td><b>Hire No.</b></td><td valign=center>H" . getHirenum($inv["invid"], 1) . "</td></tr>\r\n\t\t\t<tr><td><b>Order No.</b></td><td valign=center>{$inv['ordno']}</td></tr>\r\n\t\t\t<tr><td><b>Terms</b></td><td valign=center>Cash</td></tr>\r\n\t\t\t<tr><td><b>Invoice Date</b></td><td valign=center>{$inv['odate']}</td></tr>\r\n\t\t\t<tr><td><b>VAT</b></td><td valign=center>{$inv['chrgvat']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=3>\r\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t<tr><th>ITEM NUMBER</th><th width=45%>DESCRIPTION</th><th>QTY</th><th>UNIT PRICE</th><th>AMOUNT</th><tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t{$inv['custom_txt']}\r\n\t\t{$Com}\r\n\t</td><td align=right colspan=2>\r\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\r\n\t\t\t<tr><td><b>SUBTOTAL</b></td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\r\n\t\t\t<tr><td><b>Trade Discount</b></td><td align=right>" . CUR . " {$inv['discount']}</td></tr>\r\n\t\t\t<tr><td><b>Delivery Charge</b></td><td align=right>" . CUR . " {$inv['delivery']}</td></tr>\r\n\t\t\t<tr><td><b>VAT @ {$VATP}%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\r\n\t\t\t<tr><th><b>GRAND TOTAL<b></th><td align=right>" . CUR . " {$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n\t\t\t<tr><td colspan=2>VAT Exempt indicator = #</td></tr>\r\n\t\t\t<tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>\r\n\t</td><td><br></td></tr>\r\n\t</table></center>";
    /* Start moving invoices */
    db_connect();
    # Move invoices that are fully paid
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    $time2 = time();
    while ($invb = pg_fetch_array($invbRslt)) {
        $invb['invnum'] += 0;
        # Insert invoice to period DB
        $sql = "INSERT INTO hire.hire_invoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}')";
        //$rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.",SELF);
        $sql = "SELECT * FROM hire.monthly_invoices WHERE invid='{$invb['invid']}'";
        $hi_rslt = db_exec($sql) or errDie("Unable to retrieve hire invoice.");
        if (pg_num_rows($hi_rslt)) {
            $sql = "UPDATE hire.monthly_invoices SET invnum='{$invb['invnum']}',\r\n\t\t\t\t\t\tdeptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}',\r\n\t\t\t\t\t\tdeptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}',\r\n\t\t\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}',\r\n\t\t\t\t\t\tcusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}',\r\n\t\t\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}',\r\n\t\t\t\t\t\tchrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}',\r\n\t\t\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}',\r\n\t\t\t\t\t\todate='{$invb['odate']}', delchrg='{$invb['delchrg']}',\r\n\t\t\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}',\r\n\t\t\t\t\t\ttotal='{$invb['total']}', balance='{$invb['balance']}',\r\n\t\t\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}',\r\n\t\t\t\t\t\tdone='{$invb['done']}', div='{$invb['div']}',\r\n\t\t\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}',\r\n\t\t\t\t\t\tdelvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}',\r\n\t\t\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}',\r\n\t\t\t\t\t\tpcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}'\r\n\t\t\t\t\tWHERE invid='{$invb['invid']}'";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            $mi_invid = $invb["invid"];
        } else {
            $sql = "INSERT INTO hire.monthly_invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit, invoiced_month)";
            $sql .= " VALUES('{$invb['invid']}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}', '" . date("m") . "')";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            db_conn("hire");
            $mi_invid = pglib_lastid("monthly_invoices", "invid");
        }
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invb['invid']}'";
        $invi_rslt = db_exec($sql) or errDie("Unable to retrieve note items.");
        // 		while ($invi = pg_fetch_array($invi_rslt)) {
        // 			if (isset($monthly) && $monthly) {
        // 				$sql = "DELETE FROM hire.monthly_invitems WHERE invid='$mi_invid'";
        // 				db_exec($sql) or errDie("Unable to remove items.");
        //
        // 				$sql = "INSERT INTO hire.monthly_invitems (invid, asset_id, qty,
        // 							unitcost, amt, disc, discp, serno, div, vatcode, account,
        // 							description, basis, from_date, to_date, hours, weeks,
        // 							collection)
        // 						VALUES ('$mi_invid', '$invi[asset_id]',
        // 							'$invi[qty]', '$invi[unitcost]', '$invi[amt]',
        // 							'$invi[disc]', '$invi[discp]',	'$invi[serno]',
        // 							'".USER_DIV."',	'$invi[vatcode]', '$invi[account]',
        // 							'$invi[description]', '$invi[basis]', '$invi[from_date]',
        // 							'$invi[to_date]', '$invi[hours]', '$invi[weeks]',
        // 							'$invi[collection]')";
        // 				db_exec($sql) or errDie("Unable to create montly item.");
        // 			}
        // 		}
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('pos', '{$invb['invnum']}', '{$invb['prd']}', '', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # insert invoice items
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            $sql = "INSERT INTO hire.hire_invitems(invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}',\r\n\t\t\t\t\t\t'{$stkd['asset_id']}', '{$stkd['qty']}', '{$stkd['unitcost']}',\r\n\t\t\t\t\t\t'{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}',\r\n\t\t\t\t\t\t'{$stkd['serno']}', '" . USER_DIV . "', '{$stkd['vatcode']}',\r\n\t\t\t\t\t\t'{$stkd['account']}', '{$stkd['description']}')";
            $sql = "INSERT INTO hire.monthly_items (invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['asset_id']}',\r\n\t\t\t\t\t\t'{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}',\r\n\t\t\t\t\t\t'{$stkd['disc']}', '{$stkd['discp']}',\t'{$stkd['serno']}',\r\n\t\t\t\t\t\t'" . USER_DIV . "',\t'{$stkd['vatcode']}', '{$stkd['account']}',\r\n\t\t\t\t\t\t '{$stkd['desciption']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
    }
    // Update assets
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$inv['invid']}'";
    $item_rslt = db_exec($sql) or errDie("Unable to update items.");
    while ($item_data = pg_fetch_array($item_rslt)) {
        if (!isSerialized($item_data["asset_id"])) {
            $sql = "SELECT serial2 FROM cubit.assets\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            $qty_rslt = db_exec($sql) or errDie("Unable to retrieve qty.");
            $qty = pg_fetch_result($qty_rslt, 0);
            $qty = $qty - $item_data["qty"];
            $sql = "UPDATE cubit.assets SET serial2='{$qty}'\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to update assets.");
            $sql = "SELECT id, units FROM hire.bookings\r\n\t\t\t\t\t\tWHERE cust_id='{$inv['cusnum']}' AND\r\n\t\t\t\t\t\t\tasset_id='{$item_data['asset_id']}'";
            $bk_rslt = db_exec($sql) or errDie("Unable to retrieve booking.");
            $bk_data = pg_fetch_array($bk_rslt);
            // Update booking information.
            if (!empty($bk_data["id"])) {
                if ($bk_data["units"] - $item_data["qty"] <= 0) {
                    $sql = "DELETE FROM hire.bookings WHERE id='{$bk_data['id']}'";
                } else {
                    $new_qty = $bk_data["units"] - $item_data["qty"];
                    $sql = "UPDATE hire.bookings SET units=(units-'{$new_qty}')\r\n\t\t\t\t\t\t\t\tWHERE id='{$bk_data['id']}'";
                }
                db_exec($sql) or errDie("Unable to update bookings.");
            }
            $item_qty = $item_data["qty"];
        } else {
            $sql = "DELETE FROM hire.bookings WHERE cust_id='{$inv['cusnum']}'\r\n\t\t\t\t\t\tAND asset_id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to remove booking.");
            $item_qty = 1;
        }
        $discount = $item_data["amt"] / 100 * $inv["traddisc"];
        $sql = "INSERT INTO hire.assets_hired (invid, asset_id, hired_time, qty,\r\n\t\t\t\t\t item_id, cust_id, invnum, basis, value, discount, weekends)\r\n\t\t\t\tVALUES ('{$invid}', '{$item_data['asset_id']}', CURRENT_TIMESTAMP,\r\n\t\t\t\t\t'{$item_qty}', '{$item_data['id']}', '{$inv['cusnum']}',\r\n\t\t\t\t\t'{$inv['invnum']}', '{$item_data['basis']}', '{$item_data['amt']}',\r\n\t\t\t\t\t'{$discount}', '{$item_data['weekends']}')";
        db_exec($sql) or errDie("Unable to hire out item.");
    }
    # Commit updates
    pglib_transaction("COMMIT");
    header("Location: hire-slip.php?invid={$inv['invid']}&prd={$inv['prd']}&cccc=yes");
    exit;
}
function isHiredd($asset_id, $date = false)
{
    if (!$date) {
        $date = date("Y-m-d");
    }
    $sql = "SELECT hire_invitems.id, hours, weeks, serial, serial2,\r\n\t\t\t\tprinted, done, extract('epoch' FROM from_date) AS e_from,\r\n\t\t\t\textract('epoch' FROM to_date) AS e_to, return_time\r\n\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tLEFT JOIN hire.hire_invoices\r\n\t\t\t\t\tON hire_invitems.invid = hire_invoices.invid\r\n\t\t\t\tLEFT JOIN cubit.assets\r\n\t\t\t\t\tON hire_invitems.asset_id = assets.id\r\n\t\t\t\tLEFT JOIN hire.assets_hired\r\n\t\t\t\t\tON hire_invitems.id = assets_hired.item_id\r\n\t\t\tWHERE hire_invitems.asset_id='{$asset_id}'";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    // Check if item in workshop
    if (inWorkshop($asset_id, $date)) {
        return true;
    }
    while ($item_data = pg_fetch_array($item_rslt)) {
        if (!isSerialized($asset_id) && $item_data["serial2"] > 0) {
            return false;
        }
        if ($item_data["printed"] == "n" || $item_data["done"] == "n") {
            continue;
        }
        if (!empty($item_data["hours"])) {
            $to_date = hiredDate($item_data["id"], "U") + HOURS * $item_data["hours"];
        } elseif (!empty($item_data["weeks"])) {
            $to_date = hiredDate($item_data["id"], "U") + WEEKS * $item_data["weeks"];
        } else {
            $to_date = $item_data["e_to"];
        }
        $date = getDTEpoch("{$date} 0:00:00");
        if ($date >= $item_data["e_from"] && !$item_data["return_time"] && $date <= time()) {
            return true;
        }
        if ($date >= $item_data["e_from"] && $date <= $to_date) {
            return true;
        }
    }
    return false;
}
function details($_POST, $error = "")
{
    extract($_REQUEST);
    $fields = array();
    $fields["deptid"] = 2;
    $fields["cusnum"] = 0;
    $fields["telno"] = "";
    $fields["cordno"] = "";
    $fields["des"] = "";
    $fields["pinv_day"] = date("d");
    $fields["pinv_month"] = date("m");
    $fields["pinv_year"] = date("Y");
    $fields["vatinc_yes"] = "checked";
    $fields["vatinc_no"] = "";
    $fields["vat14"] = AT14;
    $fields["vat"] = "0.00";
    $fields["total"] = "0.00";
    $fields["rounding"] = "";
    $fields["nhifrm_year"] = date("Y");
    $fields["nhifrm_month"] = date("m");
    $fields["nhifrm_day"] = date("d");
    $fields["nhito_year"] = date("Y");
    $fields["nhito_month"] = date("m");
    $fields["nhito_day"] = date("d");
    $fields["client_collect"] = "";
    $fields["collect"] = "";
    $fields["deliver"] = "";
    $fields["deposit_amt"] = "0.00";
    $fields["deposit_type"] = "CSH";
    $fields["custom_txt"] = "";
    $fields["monthly"] = false;
    $fields["bk_asset"] = 0;
    // 30 Asset
    $fields["bk_id"] = 0;
    $fields["reprint"] = 0;
    extract($fields, EXTR_SKIP);
    if (isset($bk_from)) {
        list($nhifrm_year, $nhifrm_month, $nhifrm_day) = explode("-", $bk_from);
    }
    if (isset($bk_to)) {
        list($nhito_year, $nhito_month, $nhito_day) = explode("-", $bk_to);
    }
    $subtot = 0;
    if (isset($hirenewBtn)) {
        newHire($_POST);
    }
    // Get us an invoice id
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
    } else {
        $sql = "SELECT cusnum FROM hire.hire_invoices WHERE invid='{$invid}'";
        $cn_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
        $cusnum = pg_fetch_result($cn_rslt, 0);
        updateTotals($invid);
    }
    $ind_ccol = "";
    $ind_col = "";
    $ind_del = "";
    $collect_ar = array();
    if (!empty($client_collect)) {
        $collect_ar[] = "Client Collect";
    }
    if (!empty($collect)) {
        $collect_ar[] = "Collect";
    }
    if (!empty($deliver)) {
        $collect_ar[] = "Deliver";
    }
    if (empty($client_collect) && empty($collect) && empty($deliver)) {
        $client_collect = "checked";
        $collect_ar[] = "Client Collect";
    }
    $collection = implode(", ", $collect_ar);
    if (empty($monthly)) {
        $sql = "SELECT *, extract('epoch' FROM expected) AS e_exp, extract('epoch' FROM to_date) AS e_to FROM hire.hire_invitems WHERE invid='{$invid}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        while ($item_data = pg_fetch_array($item_rslt)) {
            if (!empty($item_data["expected"])) {
                if ($item_data["e_to"] > time()) {
                    $item_data["expected"] = date("Y-m-t", $item_data["e_to"]);
                } else {
                    if ($item_data["e_exp"] < time()) {
                        $item_data["expected"] = date("Y-m-t");
                    }
                }
                $sql = "\r\n\t\t\t\t\tUPDATE hire.hire_invitems \r\n\t\t\t\t\tSET from_date='{$item_data['to_date']}', to_date='{$item_data['expected']}', expected=NULL \r\n\t\t\t\t\tWHERE id='{$item_data['id']}'";
                db_exec($sql) or errDie("Unable to update invoice.");
            }
        }
    }
    // Retrieve the actual invoice
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    $inv_data = pg_fetch_array($inv_rslt);
    if ($cusnum == 0) {
        $cusnum = $inv_data["cusnum"];
    }
    if (empty($cordno)) {
        $cordno = $inv_data["cordno"];
    }
    $pinv_date = explode("-", $inv_data["odate"]);
    $pinv_year = $pinv_date[0];
    $pinv_month = $pinv_date[1];
    $pinv_day = $pinv_date[2];
    // Create the dropdowns ---------------------------------------------------
    // Retrieve departments
    $sql = "SELECT * FROM exten.departments ORDER BY deptname ASC";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    // Create departments dropdown
    $dept_sel = "<select name='deptid' style='width: 100%'>";
    while ($dept_data = pg_fetch_array($dept_rslt)) {
        $dept_sel .= "<option value='{$dept_data['deptid']}'>{$dept_data['deptname']}</option>";
    }
    $dept_sel .= "</select>";
    // Check customer basis
    if ($cusnum > 0) {
        checkCustBasis($cusnum);
    }
    // Retrieve customers
    $sql = "SELECT * FROM cubit.customers ORDER BY surname ASC";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
    // Create customers dropdown
    if (empty($cusnum)) {
        $cust_sel = "\r\n\t\t\t<select name='cusnum' style='width: 100%' onchange='javascript:document.form.submit()'>\r\n\t\t\t\t<option value='0'>[None]</option>";
        while ($cust_data = pg_fetch_array($cust_rslt)) {
            $sel = fsel(isset($cusnum) && $cusnum == $cust_data["cusnum"]);
            $cust_sel .= "<option value='{$cust_data['cusnum']}' {$sel}>{$cust_data['surname']}</option>";
        }
        $cust_sel .= "</select>";
    } else {
        $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$cusnum}'";
        $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
        $cust_data = pg_fetch_array($cust_rslt);
        $cust_sel = $cust_data["surname"];
    }
    // Retrieve sales people
    $sql = "SELECT * FROM exten.salespeople ORDER BY salesp ASC";
    $salesp_rslt = db_exec($sql) or errDie("Unable to retrieve sales people.");
    // Create sales people dropdown
    $salesp_sel = "<select name='salespid' style='width: 100%'>";
    while ($salesp_data = pg_fetch_array($salesp_rslt)) {
        $salesp_sel .= "<option value='{$salesp_data['salespid']}'>{$salesp_data['salesp']}</option>";
    }
    $salesp_sel .= "</select>";
    // Deposit Options
    $deposit_list = array("CSH" => "Cash", "CHQ" => "Cheque", "CRD" => "Credit Card");
    // Create the deposit dropdown
    $deposit_sel = "<select name='deposit_type'>";
    foreach ($deposit_list as $key => $value) {
        if ($inv_data["deposit_type"] == $key) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $deposit_sel .= "<option value='{$key}' {$sel}>{$value}</option>";
    }
    $deposit_sel .= "</select>";
    // Items Display -------------------------------------------------------
    $basis_list = array("per_day" => "Per Day", "per_hour" => "Per Hour", "per_week" => "Per Week");
    // Retrieve items
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}' ORDER BY id ASC";
    $items_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    $items_out = "";
    $temp_assets = array();
    while ($items_data = pg_fetch_array($items_rslt)) {
        $i = $items_data["id"];
        // Create the basis display
        $basis_disp = $basis_list[$items_data["basis"]];
        // Retrieve assets
        $sql = "SELECT * FROM cubit.assets WHERE id='{$items_data['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        $ad = pg_fetch_array($asset_rslt);
        // Retrieve asset group
        $sql = "SELECT * FROM cubit.assetgrp WHERE grpid='{$ad['grpid']}'";
        $agrp_rslt = db_exec($sql) or errDie("Unable to retrieve asset group.");
        $agrp_data = pg_fetch_array($agrp_rslt);
        if ($agrp_data["grpname"] == "Temporary Asset") {
            $temp_assets[] = $agrp_data[$ad["id"]];
        }
        // 		if ($ad["serial"] == "CUBIT::-QTY-") {
        // 			$asset_disp = "$ad[des]";
        // 		} else {
        // 			$asset_disp = "$ad[des] ($ad[serial])";
        // 		}
        $asset_disp = $ad["des"] . " " . getSerial($ad["id"], 1);
        $subtot += $items_data["amt"];
        //*$items_data["qty"];
        if ($items_data["basis"] == "per_hour") {
            $from_disp = "Hours: {$items_data['hours']}";
            $to_disp = "";
        } else {
            if ($items_data["basis"] == "per_day") {
                $mfrm_date = $items_data["from_date"];
                $mfrm_date = explode("-", $mfrm_date);
                $mfrm_year[$i] = $mfrm_date[0];
                $mfrm_month[$i] = $mfrm_date[1];
                $mfrm_day[$i] = $mfrm_date[2];
                $mto_date = $items_data["to_date"];
                $mto_date = explode("-", $mto_date);
                $mto_year[$i] = $mto_date[0];
                $mto_month[$i] = $mto_date[1];
                $mto_day[$i] = $mto_date[2];
                $from_disp = mkDateSelectA("mfrm", $i, $mfrm_year[$i], $mfrm_month[$i], $mfrm_day[$i]);
                $to_disp = mkDateSelectA("mto", $i, $mto_year[$i], $mto_month[$i], $mto_day[$i]);
                // 				$from_disp = "
                // 				<input type='hidden' name='mfrm_year[$i]' value='$mfrm_year[$i]' />
                // 				<input type='hidden' name='mfrm_month[$i]' value='$mfrm_month[$i]' />
                // 				<input type='hidden' name='mfrm_day[$i]' value='$mfrm_day[$i]' />
                // 				$mfrm_day[$i]-$mfrm_month[$i]-$mfrm_year[$i]";
                // 				$to_disp = "
                // 				<input type='hidden' name='mto_year[$i]' value='$mto_year[$i]' />
                // 				<input type='hidden' name='mto_month[$i]' value='$mto_month[$i]' />
                // 				<input type='hidden' name='mto_day[$i]' value='$mto_day[$i]' />
                // 				$mto_day[$i]-$mto_month[$i]-$mto_year[$i]";
                $from_date[$i] = "{$mfrm_year[$i]}-{$mfrm_month[$i]}-{$mfrm_day[$i]}";
                $to_date[$i] = "{$mto_year[$i]}-{$mto_month[$i]}-{$mto_day[$i]}";
                $hidden_date = "\r\n\t\t\t\t\t<input type='hidden' name='from_date[{$i}]' value='{$from_date[$i]}' />\r\n\t\t\t\t\t<input type='hidden' name='to_date[{$i}]' value='{$to_date[$i]}' />";
                // 				$from_disp = "$items_data[from_date]";
                // 				$to_disp = "$items_data[to_date]";
            } else {
                if ($items_data["basis"] == "per_week") {
                    $from_disp = "Weeks: {$items_data['weeks']}";
                    $to_disp = "";
                }
            }
        }
        if (!isset($return[$i])) {
            $return[$i] = "";
        }
        if (!isset($hidden_date)) {
            $hidden_date = "";
        }
        if (!isset($rain_days[$i])) {
            $rain_days[$i] = 0;
        }
        if ($items_data["basis"] == "per_day") {
            $rd_disp = "<input type='hidden' name='rain_days[{$i}]' \t\t\t\r\n\t\t\t\t\t\tvalue='{$rain_days[$i]}' size='3' style='text align: center' />";
            if ($items_data["half_day"]) {
                //				$hd_disp = "<input type='checkbox' name='half_day[$i]' value='1' checked /> Half Day</b>";
                $hd_disp = "<input type='hidden' name='half_day[{$i}]' value='1' />";
            } else {
                $hd_disp = "<input type='hidden' name='half_day[{$i}]' value='0' />";
                //				$hd_disp = "<input type='checkbox' name='half_day[$i]' value='1' /> Half Day";
            }
        } else {
            $hd_disp = "";
            $rd_disp = "<input type='hidden' name='rain_days[{$i}]' value='0' />";
        }
        if ($items_data["weekends"]) {
            $weekends[$i] = "checked";
        } else {
            $weekends[$i] = "";
        }
        // Items should not be removed once processed, use reprint to check
        // if this hire note has already been processed.
        if (isset($reprint) && $reprint || !empty($monthly)) {
            $rem_cbox = "";
        } else {
            $rem_cbox = "<td><input type='checkbox' name='remove[{$i}]'></td>";
        }
        if (isset($monthly) && $monthly) {
            if ($items_data["basis"] == "per_day") {
                $ret_cbox = "<td><input type='checkbox' name='return[{$i}]' value='checked' {$return[$i]}></td>";
            } else {
                $ret_cbox = "<td>&nbsp;</td>";
            }
        } else {
            $ret_cbox = "<td><input type='checkbox' name='return[{$i}]' value='checked' {$return[$i]}></td>";
        }
        $amt = sprint($items_data["amt"]);
        if (user_is_admin(USER_ID)) {
            $amount_out = "<input type='text' name='amount[{$i}]' value='{$amt}' size='7' />";
        } else {
            $amount_out = "<input type='hidden' name='amount[{$i}]' value='{$amt}' />{$amt}";
        }
        $items_out .= "\r\n\t\t\t<input type='hidden' name='asset_id[{$i}]' value='{$ad['id']}' />\r\n\t\t\t<input type='hidden' name='basis[{$i}]' value='{$items_data['basis']}' />\r\n\t\t\t<input type='hidden' name='qty[{$i}]' value='{$items_data['qty']}' />\r\n\t\t\t{$hidden_date}\r\n\t\t\t{$rd_disp}\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$basis_disp}</td>\r\n\t\t\t\t<td>{$asset_disp}</td>\r\n\t\t\t\t<td align='center'>{$items_data['qty']}</td>\r\n\t\t\t\t<td align='center'>{$from_disp}</td>\r\n\t\t\t\t<td align='center'>{$to_disp} {$hd_disp}</td>\r\n\t<!--\t\t\t\r\n\t\t\t\t<td align='center'>{$rd_disp}</td>\r\n\t\t\t\t<td align='center'>{$items_data['collection']}</td>\r\n\t-->\r\n\t\t\t\t<td>{$amount_out}</td>\r\n\t\t\t\t{$rem_cbox}\r\n\t\t\t\t{$ret_cbox}\r\n\t\t\t</tr>";
    }
    $temp_assets = implode(",", $temp_assets);
    // New Items --------------------------------------------------------------
    // Avoid undefined variable items_out
    if (empty($items_out)) {
        $items_out = "";
    }
    // Buttons
    if (!empty($cusnum)) {
        if ($deposit_type == "CSH" && $deposit_amt != "0.00") {
            $deposit_open = "popupOpen(\"hire-invoice-print.php?key=cash_receipt&invid={$inv_data['invid']}\")";
        } else {
            $deposit_open = "";
        }
        $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$cusnum}'";
        $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
        $cust_data = pg_fetch_array($cust_rslt);
        $telno = $cust_data["bustel"];
        $return_btn = "<input type='submit' name='upBtn' value='Return' />";
        if (isset($reprint) && $reprint) {
            $new_btn = "<input type='button' value='Reprint' onclick='javascript:printer(\"hire/hire_note_reprint.php?invid={$inv_data['invid']}\");{$deposit_open}'>";
            $purch_btn = "";
            //$purch_btn = "<input type='button' value='Payment' onclick='javascript:popupOpen(\"".SELF."?key=newpos&cusnum=$cusnum\");' />";
        } else {
            if (!$monthly) {
                $new_btn = "<input name='hirenewBtn' type='submit' value='Process' />";
            } else {
                $new_btn = "<input type='submit' name='upBtn' value='Invoice' />";
            }
            $purch_btn = "";
        }
        $hire_buttons = "\r\n\t\t\t<tr>\r\n\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t<td align='center'>\r\n\t\t\t\t\t<input type='submit' name='upBtn' value='Update'>\r\n\t\t\t\t\t{$new_btn}\r\n\t\t\t\t\t{$return_btn}\r\n\t\t\t\t\t{$purch_btn}\r\n\t\t\t\t\t<!--<input type='button' value='Swap Hire' />-->\r\n\t\t\t\t</td>\r\n\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t</tr>";
        $basevis = "visible";
        $credit_limit = CUR . sprint($cust_data["credlimit"] - $cust_data["balance"]);
        $cust_balance = CUR . $cust_data["balance"];
    } else {
        $hire_buttons = "";
        $basevis = "hidden";
        $credit_limit = "";
        $cust_balance = "";
    }
    // Retrieve assets
    $sql = "SELECT *  FROM cubit.assets ORDER BY des ASC";
    $nasset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
    // Assets dropdown
    $nasset_sel = "\r\n\t\t<select name='nasset_id' style='visibility: {$basevis}; width: 120px' onchange='assetChange(this);'>\r\n\t\t\t<option value='0'>- SELECT PLANT -</option>";
    while ($ad = pg_fetch_array($nasset_rslt)) {
        $sql = "SELECT * FROM hire.hire_invitems WHERE asset_id='{$ad['id']}' AND invid='{$invid}'";
        $invitem_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        if (pg_num_rows($invitem_rslt)) {
            continue;
        }
        if (!empty($ad["remaction"])) {
            continue;
        }
        if (isHired($ad["id"], date("Y-m-d"))) {
            continue;
        }
        if (!isSerialized($ad["id"])) {
            $at = "q";
            //$asset_disp = "$ad[des] ($ad[serial2] available.)";
            $units_avail = unitsAvailable($ad["id"], date("Y-m-d"));
            $asset_disp = "{$ad['des']} {$units_avail} available.";
            if ($ad["serial2"] <= 0) {
                continue;
            }
        } else {
            $at = "s";
            $asset_disp = "{$ad['des']} ({$ad['serial']})";
        }
        if ($cust_bk = isBooked($ad["id"], date("Y-m-d"))) {
            $sql = "SELECT surname FROM cubit.customers WHERE cusnum='{$cust_bk}'";
            $surname_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
            $surname = pg_fetch_result($surname_rslt, 0);
            if (isSerialized($ad["id"])) {
                $asset_disp .= " Booked: {$surname}";
            } else {
                $units_booked = unitsBooked($ad["id"], date("Y-m-d"));
                $asset_disp .= " {$units_booked} Units Booked";
            }
        }
        if ($bk_asset == $ad["id"]) {
            $sel = "selected='selected'";
        } else {
            $sel = "";
        }
        $nasset_sel .= "<option value='{$at}:{$ad['id']}' {$sel}>{$asset_disp}</option>";
    }
    $nasset_sel .= "</select>";
    // Create basis dropdown
    $nbasis_sel = "\r\n\t\t<select name='nbasis' style='width: 100%; visibility: {$basevis};' onchange='basisChange(this);'>\r\n\t\t\t<option value='0'>- BASIS -</option>";
    foreach ($basis_list as $key => $value) {
        $nbasis_sel .= "<option value='{$key}'>{$value}</option>";
    }
    $nbasis_sel .= "</select>";
    // Create asset group dropdown
    $sql = "SELECT grpid, grpname FROM cubit.assetgrp ORDER BY grpname ASC";
    $grp_rslt = db_exec($sql) or errDie("Unable to retrieve groups.");
    if ($cusnum) {
        $OTS_OPT = onthespot_encode(SELF, "cust_selection", "deptid={$deptid}&cusnum={$cusnum}&invid={$invid}");
        // 		$cust_edit = "
        // 			<td nowrap>
        // 			<a href='javascript: popupSized(\"../cust-edit.php?cusnum=$cusnum&onthespot=$OTS_OPT\", \"edit_cust\", 700, 630);'>
        // 				Edit Customer Details
        // 			</a>
        // 			</td>";
        $cust_edit = "";
    } else {
        $cust_edit = "";
    }
    // Retrieve service date
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
    $invi_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
    $sv_warn = "";
    while ($invi_data = pg_fetch_array($invi_rslt)) {
        $sql = "SELECT * FROM cubit.asset_svdates WHERE svdate<=CURRENT_DATE AND asset_id='{$invi_data['asset_id']}'";
        $sv_rslt = db_exec($sql) or errDie("Unable to retrieve service date.");
        $sv_data = pg_fetch_array($sv_rslt);
        // Retrieve asset
        if (pg_num_rows($sv_rslt)) {
            $sql = "SELECT * FROM cubit.assets WHERE id='{$sv_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
            $asset_data = pg_fetch_array($asset_rslt);
            $sv_warn .= "<li class='err'><b>SERVICING</b>: " . getSerial($asset_data["id"], 1) . "\r\n\t\t\t{$asset_data['des']} has a service date on {$sv_data['svdate']}.</li>";
        }
        if ($days = checkServicing($invi_data["asset_id"], 1)) {
            $sv_warn .= "<li class='err'><b>SERVICING</b>: {$asset_data['des']} needs servicing.</li>";
        }
    }
    // Check if we should use the default comments
    if (empty($inv_data["comm"])) {
        $sql = "SELECT value FROM cubit.settings WHERE constant='HIRE_COMMENTS'";
        $comment_rslt = db_exec($sql) or errDie("Unable to retrieve comments.");
        $inv_data["comm"] = pg_fetch_result($comment_rslt, 0);
    }
    // Site address
    $addr_sel = "";
    if ($cusnum) {
        // Retrieve branch address
        $sql = "SELECT branch_addr FROM hire.hire_invoices WHERE invid='{$invid}'";
        $addr_rslt = db_exec($sql) or errDie("Unable to retrieve branch address.");
        $branch_addr = pg_fetch_result($addr_rslt, 0);
        $sql = "SELECT id, branch_name FROM cubit.customer_branches WHERE cusnum='{$cusnum}'";
        $bran_rslt = db_exec($sql) or errDie("Unable to retrieve customer branch.");
        $addr_sel = "<select name='branch_addr' style='width: 100%' onchange='javascript:document.form.submit()'>";
        $addr_sel .= "<option value='0'>Physical Address</option>";
        while ($bran_data = pg_fetch_array($bran_rslt)) {
            if ($branch_addr == $bran_data["id"]) {
                $sel = "selected='selected'";
            } else {
                $sel = "";
            }
            $addr_sel .= "<option value='{$bran_data['id']}' {$sel}>{$bran_data['branch_name']}</option>";
        }
        $addr_sel .= "</select>";
        $addr_sel .= "<br />" . branchAddress($branch_addr, $cusnum);
    }
    $booked_items = getBookedItems($cusnum, date("Y-m-d"));
    foreach ($booked_items as $asset_id => $units_booked) {
        $sql = "SELECT des FROM cubit.assets WHERE id='{$asset_id}'";
        $bkdes_rslt = db_exec($sql) or errDie("Unable to retrieve bookings.");
        $bkdes = pg_fetch_result($bkdes_rslt, 0);
        $sv_warn .= "<li class='err'><b>BOOKING</b>: {$units_booked}x " . getSerial($asset_id, 1) . " {$bkdes} booked for this customer.</li>";
    }
    if ($monthly) {
        $ret_out = "Invoice";
    } else {
        $ret_out = "Return";
    }
    // Items should not be removed once processed, use reprint to check
    // if this hire note has already been processed or if its monthly.
    if (isset($reprint) && $reprint || !empty($monthly)) {
        $rem_th = "";
        $rem_nbsp = "";
    } else {
        $rem_th = "<th>Remove</th>";
        $rem_nbsp = "<td>&nbsp;</td>";
    }
    // Use the customer trad discount on default
    $sql = "SELECT traddisc FROM cubit.customers WHERE cusnum='{$cusnum}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
    $trade_discount = pg_fetch_result($cust_rslt, 0);
    // Determine if we got any items, if we do, we don't need to go for the
    // default value anymore, because the customer is already selected.
    $sql = "SELECT count(id) FROM hire.hire_invitems WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    $count = pg_fetch_result($count_rslt, 0);
    if ($count) {
        $trade_discount = $inv_data["traddisc"];
    }
    if (isset($bk_id) && $bk_id && !isset($bk_done)) {
        $sql = "\r\n\t\t\tSELECT serial FROM hire.bookings\r\n\t\t\t\tLEFT JOIN cubit.assets ON bookings.asset_id=assets.id\r\n\t\t\tWHERE bookings.id='{$bk_id}'";
        $bk_rslt = db_exec($sql) or errDie("Unable to retrieve booking.");
        $serialized = pg_fetch_result($bk_rslt, 0);
        if ($serialized == "Not Serialized") {
            $qty_disabled = "";
        } else {
            $qty_disabled = "disabled='t'";
        }
    } else {
        $qty_disabled = "disabled='t'";
    }
    // New Items
    $new_items_out = "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>{$nbasis_sel}</td>\r\n\t\t\t<td>{$nasset_sel}</td>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<input type='text' id='nqty' name='nqty' value='' size='3' class='clear' {$qty_disabled} style='text-align:center' />\r\n\t\t\t</td>\r\n\t\t\t<td align='left' nowrap='t'>\r\n\t\t\t\t<div id='d_wks' style='height: 0px; visibility: hidden;'>\r\n\t\t\t\t\tWeeks: <input type='text' name='weeks' size='5' style='text-align: center;' />\r\n\t\t\t\t</div>\r\n\t\t\t\t<div id='d_hrs' style='height: 0px; visibility: hidden;'>\r\n\t\t\t\t\tHours: <input type='text' name='hours' size='5'\r\n\t\t\t\t\t\tstyle='text-align: center;' />\r\n\t\t\t\t</div>\r\n\t\t\t\t<div id='d_fdate' style='visibility: hidden;'>\r\n\t\t\t\t\t" . mkDateSelect("nhifrm", $nhifrm_year, $nhifrm_month, $nhifrm_day) . "\r\n\t\t\t\t</div>\r\n\t\t\t</td>\r\n\t\t\t<td align='left' nowrap='t'>\r\n\t\t\t\t<div id='d_tdate' style='visibility: hidden;'>\r\n\t\t\t\t\t" . mkDateSelect("nhito", $nhito_year, $nhito_month, $nhito_day) . "\r\n\t<!--\t\t\t\t\r\n\t\t\t\t\t<input type='checkbox' name='nhalf_day' value='checked' />\r\n\t\t\t\t\tHalf Day\r\n\t-->\t\t\t\r\n\t\t\t\t</div>\r\n\t\t\t</td>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t\t{$rem_nbsp}\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t</tr>";
    /* -- Final Layout -- */
    $details = "\r\n\t\t<script>\r\n\t\t\tfunction basisChange(o) {\r\n\t\t\t\thrs = getObject('d_hrs');\r\n\t\t\t\tfd = getObject('d_fdate');\r\n\t\t\t\ttd = getObject('d_tdate');\r\n\t\t\t\twks = getObject('d_wks');\r\n\r\n\t\t\t\tswitch (o.value) {\r\n\t\t\t\t\tcase 'per_hour':\r\n\t\t\t\t\t\thrs.style.visibility = 'visible';\r\n\t\t\t\t\t\tfd.style.visibility = 'hidden';\r\n\t\t\t\t\t\ttd.style.visibility = 'hidden';\r\n\t\t\t\t\t\twks.style.visibility = 'hidden';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'per_day':\r\n\t\t\t\t\t\thrs.style.visibility = 'hidden';\r\n\t\t\t\t\t\tfd.style.visibility = 'visible';\r\n\t\t\t\t\t\ttd.style.visibility = 'visible';\r\n\t\t\t\t\t\twks.style.visibility = 'hidden';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'per_week':\r\n\t\t\t\t\t\thrs.style.visibility = 'hidden';\r\n\t\t\t\t\t\tfd.style.visibility = 'hidden';\r\n\t\t\t\t\t\ttd.style.visibility = 'hidden';\r\n\t\t\t\t\t\twks.style.visibility = 'visible';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\thrs.style.visibility = 'hidden';\r\n\t\t\t\t\t\tfd.style.visibility = 'hidden';\r\n\t\t\t\t\t\ttd.style.visibility = 'hidden';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfunction assetChange(o) {\r\n\t\t\t\tqo = getObject('nqty');\r\n\r\n\t\t\t\tswitch(o.value.substr(0, 1)) {\r\n\t\t\t\t\tcase 'q':\r\n\t\t\t\t\t\tqo.value = '';\r\n\t\t\t\t\t\tqo.disabled = false;\r\n\t\t\t\t\t\tqo.className = 'std';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 's':\r\n\t\t\t\t\t\tqo.value = '1';\r\n\t\t\t\t\t\tqo.disabled = true;\r\n\t\t\t\t\t\tqo.className = 'clear';\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tqo.value = '';\r\n\t\t\t\t\t\tqo.disabled = true;\r\n\t\t\t\t\t\tqo.className = 'clear'\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t</script>\r\n\t\t<style>\r\n\t\t\ttd, input, textarea, select { font-size: .75em; }\r\n\t\t</style>\r\n\t\t<center>\r\n\t\t<form method='POST' name='formName'>\r\n\t\t\t<input type='hidden' name='key' value='update'>\r\n\t\t</form>\r\n\t\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t\t\t<input type='hidden' name='collection' value='{$collection}' />\r\n\t\t\t<input type='hidden' name='key' value='update'>\r\n\t\t\t<input type='hidden' name='invid' value='{$invid}' />\r\n\t\t\t<input type='hidden' name='temp_assets' value='{$temp_assets}' />\r\n\t\t\t<input type='hidden' name='monthly' value='{$monthly}' />\r\n\t\t\t<input type='hidden' name='cusnum' value='{$cusnum}' />\r\n\t\t\t<input type='hidden' name='chrgvat' value='no' />\r\n\t\t\t<input type='hidden' name='bk_id' value='{$bk_id}' />\r\n\t\t\t<input type='hidden' name='bk_done' value='1' />\r\n\t\t\t<input type='hidden' name='reprint' value='{$reprint}' />\r\n\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t \t<tr>\r\n\t\t \t\t<td colspan='3' align='center'><h3>New Hire</h3></td>\r\n\t\t \t</tr>\r\n\t\t \t<tr>\r\n\t\t \t\t<td valign='top'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Department</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$dept_sel}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$cust_sel}</td>\r\n\t\t\t\t\t\t\t{$cust_edit}\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer Telephone Number</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='text' size='20' name='telno' value='{$telno}'>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='text' size='10' name='cordno' value='{$cordno}'>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Available Credit</td>\r\n\t\t\t\t\t\t\t<td>{$credit_limit}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Balance</td>\r\n\t\t\t\t\t\t\t<td>{$cust_balance}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t<td>{$addr_sel}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t<!--\r\n\t\t\t\t\t\t<tr><th colspan='2'>Point of Hire</th></tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Barcode</td>\r\n\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t<input type='text' size='13' name='bar' value=''>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td nowrap='t'>Search for description</td>\r\n\t\t\t\t\t\t\t<td><input type='text' size='13' name='des' value='{$des}'></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td colspan='2' align='center'>\r\n\t\t\t\t\t\t\t\t<input type='submit' value='Search'>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Collection Method</td>\r\n\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t<input type='checkbox' name='client_collect' value='checked' {$client_collect} />\r\n\t\t\t\t\t\t\t\tClient Collect\r\n\t\t\t\t\t\t\t\t<br />\r\n\t\t\t\t\t\t\t\t<input type='checkbox' name='deliver' value='checked' {$deliver} />\r\n\t\t\t\t\t\t\t\tTo be Delivered\r\n\t\t\t\t\t\t\t\t<br />\r\n\t\t\t\t\t\t\t\t<input type='checkbox' name='collect' value='checked' {$collect} />\r\n\t\t\t\t\t\t\t\tTo be Collected\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t-->\r\n\t\t\t\t\t</table>\r\n\t\t\t\t<td valign='top' align='center' style='width: 100%;'>\r\n\t\t\t\t\t<img src='../compinfo/getimg.php' style='border: 1px solid #000' width='230' height='47' />\r\n\t\t\t\t</td>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td valign='top' align='right'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan=2>Hire Details</th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Hire No.</td>\r\n\t\t\t\t\t\t\t<td valign='center'>H{$inv_data['invnum']}" . rev($inv_data["invid"]) . "</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Sales Order No.</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='text' size='5' name='ordno' value='{$inv_data['ordno']}'>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Hire Date</td>\r\n\t\t\t\t\t\t\t<td valign='center' nowrap='t'>\r\n\t\t\t\t\t\t\t\t" . mkDateSelect("pinv", $pinv_year, $pinv_month, $pinv_day) . "\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Sales Person</td>\r\n\t\t\t\t\t\t\t<td>{$salesp_sel}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Trade Discount</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='text' size='5' name='traddisc'\r\n\t\t\t\t\t\t\t\tvalue='{$trade_discount}'>%\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td nowrap='t'>Delivery Charge</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='text' size='7' name='delchrg'\r\n\t\t\t\t\t\t\t\tvalue='{$inv_data['delchrg']}'>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'>Payment Details </th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>User</td>\r\n\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t<input type='hidden' name='user' value='" . USER_NAME . "'>\r\n\t\t\t\t\t\t\t\t" . USER_NAME . "\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Deposit Type</td>\r\n\t\t\t\t\t\t\t<td>{$deposit_sel}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Deposit Amount</td>\r\n\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t<input type='text' name='deposit_amt'\r\n\t\t\t\t\t\t\t\tvalue='" . sprint($inv_data["deposit_amt"]) . "' size='7' />\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='3'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'></tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th>Basis</th>\r\n\t\t\t\t\t\t\t<th>Item</th>\r\n\t\t\t\t\t\t\t<th>Qty</th>\r\n\t\t\t\t\t\t\t<th>Hire Date</th>\r\n\t\t\t\t\t\t\t<th>Expected Return</th>\r\n\t\t\t<!--\t\t\t\r\n\t\t\t\t\t\t\t<th>Rain Days</th>\r\n\t\t\t\t\t\t\t<th>Collection</th>\r\n\t\t\t-->\r\n\t\t\t\t\t\t\t<th>Amount</th>\r\n\t\t\t\t\t\t\t{$rem_th}\r\n\t\t\t\t\t\t\t<th>{$ret_out}</th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t{$items_out}\r\n\t\t\t\t\t\t{$new_items_out}\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td width='70%' valign='top' colspan='2'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td colspan='10'>{$sv_warn}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td rowspan='4' nowrap>" . mkQuickLinks(ql("javascript:popupOpen(\"../customers-new.php\")", "New Customer"), ql("../pos-invoice-new.php", "New POS Invoice"), ql("../nons-invoice-new.php", "New Non-Stock Invoice")) . "\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<th>Comments</th>\r\n\t\t\t\t\t\t\t<th>Custom Text</th>\r\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width=40%>{$error}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td rowspan=4 align=center valign=top>\r\n\t\t\t\t\t\t\t\t<textarea name=comm cols=20 style='height: 100%'>{$inv_data['comm']}</textarea>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td rowspan='4' align='center' valign='top'>\r\n\t\t\t\t\t\t\t\t<textarea name='custom_txt' rows='4' cols='60' style='height: 100%'>{$custom_txt}</textarea>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td colspan='2' align='right' valign='top' width='30%'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Delivery Charge</td>\r\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$inv_data['delivery']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Trade Discount</td>\r\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$inv_data['discount']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\r\n\t\t\t\t\t\t\t<td align=right>\r\n\t\t\t\t\t\t\t\t" . CUR . "<input type=hidden name='subtot' value='{$inv_data['subtot']}'>\r\n\t\t\t\t\t\t\t\t" . sprint($inv_data["subtot"]) . "\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\r\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$inv_data['vat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\r\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$inv_data['total']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t{$rounding}\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t{$hire_buttons}\r\n\t\t</table>\r\n\t\t<a name='bottom'>\r\n\t\t</form>\r\n\t\t</center>";
    return $details;
}
Example #25
0
// SAVE
//
$user = Session::get_session_user();
$name_layout = POST('name');
$layout = POST('layout');
$category = POST('category');
if ($category == '') {
    $category = 'policy';
}
ossim_valid($name_layout, OSS_ALPHA, OSS_SCORE, OSS_NULLABLE, 'illegal:' . _("name_layout"));
ossim_valid($layout, OSS_TEXT, OSS_PUNC_EXT, OSS_NULLABLE, 'illegal:' . _("layout"));
ossim_valid($category, OSS_ALPHA, OSS_NULLABLE, 'illegal:' . _("category"));
if (ossim_error()) {
    die(ossim_error());
}
//$text_layout = unserialize(stripslashes($layout));
//print_r(stripslashes($layout));
if ($user != "" && $name_layout != "" && isSerialized($layout)) {
    if (POST('type') == 'file') {
        $file = "/tmp/" . $user . "_" . $name_layout;
        $f = fopen($file, "w");
        fputs($f, trim($layout));
        fclose($f);
    } else {
        $db = new ossim_db();
        $conn = $db->connect();
        $config = new User_config($conn);
        $config->set($user, $name_layout, $layout, 'simple', $category);
    }
    echo _("Layout saved!");
}
Example #26
0
 function retrieve($packed)
 {
     if (is_string($packed) and substr($packed, 0, 2) == "a:") {
         $packed = unserialize($packed);
     }
     if (!is_array($packed)) {
         return false;
     }
     $prefs = array();
     foreach ($packed as $name => $packed_pref) {
         if (is_string($packed_pref) and isSerialized($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
             //legacy: check if it's an old array of objects
             // Looks like a serialized object.
             // This might fail if the object definition does not exist anymore.
             // object with ->$name and ->default_value vars.
             $pref = @unserialize($packed_pref);
             if (is_object($pref)) {
                 $prefs[$name] = $pref->get($name);
             }
             // fix old-style prefs
         } elseif (is_numeric($name) and is_array($packed_pref)) {
             if (count($packed_pref) == 1) {
                 list($name, $value) = each($packed_pref);
                 $prefs[$name] = $value;
             }
         } else {
             if (isSerialized($packed_pref)) {
                 $prefs[$name] = @unserialize($packed_pref);
             }
             if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref))) {
                 $prefs[$name] = @unserialize(base64_decode($packed_pref));
             }
             // patched by frederik@pandora.be
             if (empty($prefs[$name])) {
                 $prefs[$name] = $packed_pref;
             }
         }
     }
     if (FUSIONFORGE) {
         // Restore notifyPages from notifyPagesAll
         // notifyPages are pages to notify in the current project
         // while $notifyPagesAll is used to store all the monitored pages.
         if (isset($prefs['notifyPages'])) {
             $this->notifyPagesAll = $prefs['notifyPages'];
             if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
                 $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
             } else {
                 $prefs['notifyPages'] = '';
             }
         }
     }
     return $prefs;
 }
Example #27
0
<?php

/* Prototype  : proto string serialize(mixed variable)
 * Description: Returns a string representation of variable (which can later be unserialized)
 * Source code: ext/standard/var.c
 * Alias to functions:
 */
/* Prototype  : proto mixed unserialize(string variable_representation)
 * Description: Takes a string representation of variable and recreates it
 * Source code: ext/standard/var.c
 * Alias to functions:
 */
echo "*** Testing unserialize() error/boolean distinction ***\n";
$garbage = "obvious non-serialized data";
$serialized_false = serialize(false);
var_dump($serialized_false);
$deserialized_garbage = unserialize($garbage);
var_dump($deserialized_garbage);
$deserialized_false = unserialize($serialized_false);
var_dump($deserialized_false);
echo "unserialize error and deserialized false are identical? " . (bool) ($deserialized_false == $deserialized_garbage) . "\n";
// candidate safe idiom for determining whether data is serialized
function isSerialized($str)
{
    return $str == serialize(false) || @unserialize($str) !== false;
}
// Test unserialize error idiom
var_dump(isSerialized($garbage));
var_dump(isSerialized($serialized_false));
echo "Done";