Пример #1
0
 function init()
 {
     $this->module_name = "language";
     $language_code = basename(module_config::c('default_language'));
     if (module_security::is_logged_in()) {
         $user = module_user::get_user(module_security::get_loggedin_id(), false);
         if ($user && $user['user_id'] && isset($user['language']) && $user['language']) {
             $language_code = basename($user['language']);
         }
     }
     // language code, like en, gb, etc..
     self::set_ui_language($language_code);
 }
Пример #2
0
 public function init()
 {
     $this->links = array();
     $this->help_types = array();
     $this->module_name = "help";
     $this->module_position = 16;
     $this->version = 2.11;
     //2.11 - 2014-04-05 - url help js
     //2.1 - 2014-03-14 - initial release of new help system
     if (module_help::is_plugin_enabled() && (module_config::c('help_only_for_admin', 1) && module_security::get_loggedin_id() == 1 || !module_config::c('help_only_for_admin', 1) && module_help::can_i('view', 'Help'))) {
         // hook for help icon in top bar
         hook_add('header_buttons', 'module_help::hook_filter_var_header_buttons');
         hook_add('header_print_js', 'module_help::header_print_js');
         module_config::register_js('help', 'help.js');
         if (module_config::can_i('view', 'Settings')) {
             $this->links[] = array("name" => "Help", "p" => "help_settings", 'holder_module' => 'config', 'holder_module_page' => 'config_admin', 'menu_include_parent' => 0);
         }
     }
 }
Пример #3
0
<?php

/** 
 * Copyright: dtbaker 2012
 * Licence: Please check CodeCanyon.net for licence details. 
 * More licence clarification available here:  http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ 
 * Deploy: 9809 f200f46c2a19bb98d112f2d32a8de0c4
 * Envato: 4ffca17e-861e-4921-86c3-8931978c40ca, 0a3014a3-2b8f-460b-8850-d6025aa845f8
 * Package Date: 2015-11-25 03:08:08 
 * IP Address: 67.79.165.254
 */
if (class_exists('module_customer', false) && module_security::can_user(module_security::get_loggedin_id(), 'Show Dashboard Widgets')) {
    $customer_types = module_customer::get_customer_types();
    foreach ($customer_types as $customer_type) {
        // if(!empty($customer_type['type_name_plural']) && $customer_type['customer_type_id']) { // dtbaker
        if (!empty($customer_type['type_name_plural'])) {
            // dtbaker
            if (module_customer::can_i('view', $customer_type['type_name_plural'])) {
                // find out how many open customers are left..
                $customers = module_customer::get_customers(array('customer_type_id' => $customer_type['customer_type_id']), true);
                ob_start();
                // icons from http://ionicons.com/
                ?>

				<div class="small-box bg-yellow">
					<div class="inner">
						<h3>
							<?php 
                echo mysql_num_rows($customers);
                ?>
						</h3>
Пример #4
0
            <div class="content_box_wheader" style="padding-bottom: 20px">
                <p>
                    <?php 
    _e('This ticket is not assigned to anyone.');
    ?>
<br/>
                    <?php 
    _e('If you are able to solve this ticket please assign it to yourself.');
    ?>

                </p>
                <input type="button" name="butt_assign_me" value="<?php 
    _e('Assign this ticket to me');
    ?>
" class="submit_button btn btn-success" onclick="$('#assigned_user_id').val(<?php 
    echo module_security::get_loggedin_id();
    ?>
); this.form.submit();">
	            <p>
		            <?php 
    _e('If you cannot solve this ticket please assign it to someone else in the drop down list.');
    ?>

	            </p>
            </div>
            <?php 
    $fieldset_data = array('heading' => array('title' => _l('Unassigned Ticket'), 'type' => 'h3'), 'elements_before' => ob_get_clean());
    echo module_form::generate_fieldset($fieldset_data);
    unset($fieldset_data);
}
/** TICKET MESSAGES */
Пример #5
0
 public function has_viewed()
 {
     // close off any notifications here.
     if ($this->file_id > 0) {
         $sql = "UPDATE `" . _DB_PREFIX . "file_notification` SET `view_time` = '" . time() . "' WHERE `view_time` = 0 AND `user_id` = " . module_security::get_loggedin_id() . " AND file_id = " . (int) $this->file_id;
         query($sql);
     }
 }
Пример #6
0
    echo _l($link['name']);
    ?>
				</a>
			</li>
		<?php 
}
unset($menu_holder);
unset($menu_type);
unset($current_link);
unset($menu_allow_nesting);
?>
        <?php 
if (isset($show_quick_search) && $show_quick_search) {
    ?>
        <?php 
    if (module_security::getcred() && module_security::can_user(module_security::get_loggedin_id(), 'Show Quick Search') && $display_mode != 'mobile') {
        if (module_config::c('global_search_focus', 1) == 1) {
            module_form::set_default_field('ajax_search_text');
        }
        ?>
            <li>
                <div id="quick_search_box">
                    <div id="quick_search_placeholder"><div><?php 
        _e('Quick Search:');
        ?>
</div></div>
                    <input type="text" name="quick_search" id="ajax_search_text" size="10" value="">
                    <div id="ajax_search_result"></div>
                </div>
            </li>
         <?php 
Пример #7
0
        <!-- end header.head -->


    </div>
    <!-- /#top -->

    <?php 
            if (module_security::getcred()) {
                ?>

    <div id="left">

        <div class="media user-media">
            <div class="media-body">
                <h5 class="media-heading"><?php 
                $user = module_user::get_user(module_security::get_loggedin_id());
                _e('Welcome %s', htmlspecialchars($user['name']));
                ?>
</h5>
                <ul class="list-unstyled user-info">
                    <li><small><i class="fa fa-user"></i> <a href="<?php 
                echo module_user::link_open($_SESSION['_user_id']);
                ?>
"><?php 
                _e('Edit Profile');
                ?>
</a></small></li>
	                <?php 
                $header_buttons = array();
                if (module_security::is_logged_in()) {
                    $header_buttons = hook_filter_var('header_buttons', $header_buttons);
Пример #8
0
        ?>

                </td>
                <td valign="top">
                    <input type="text" name="job_task[new][date_due]" value="<?php 
        echo print_date($job['date_due']);
        ?>
" class="date_field">
                </td>
                <?php 
        if (module_config::c('job_allow_staff_assignment', 1)) {
            ?>

                    <td valign="top">
                        <?php 
            echo print_select_box($staff_member_rel, 'job_task[new][user_id]', isset($staff_member_rel[module_security::get_loggedin_id()]) ? module_security::get_loggedin_id() : false, 'job_task_staff_list', '');
            ?>

                    </td>
                <?php 
        }
        ?>

                <td valign="top">
                    <input type="checkbox" name="job_task[new][new_fully_completed]" value="1">
                </td>
                <td align="center" valign="top">
                    <input type="submit" name="save" value="<?php 
        _e('New Task');
        ?>
" class="save_task small_button">
Пример #9
0
    public static function hook_job_task_after($hook, $job_id, $task_id, $job_data, $task_data)
    {
        $comments = get_multiple('job_discussion', array('job_id' => $job_id, 'task_id' => $task_id), 'job_discussion_id', 'exact', 'job_discussion_id');
        if ($job_data && isset($job_data['job_discussion']) && $job_data['job_discussion'] == 1) {
            // disabled & hidden.
            return;
        }
        if ($job_data && isset($job_data['job_discussion']) && $job_data['job_discussion'] == 2 && count($comments) == 0) {
            // disabled & shown.
            return;
        }
        if (isset($_POST['job_discussion_add_job_id']) && isset($_POST['job_discussion_add_task_id']) && $_POST['job_discussion_add_job_id'] == $job_id && $_POST['job_discussion_add_task_id'] == $task_id && isset($_POST['note']) && strlen($_POST['note'])) {
            $x = 0;
            while (ob_get_level() && $x++ < 10) {
                ob_end_clean();
            }
            $current_user_id = module_security::get_loggedin_id();
            $customer = module_customer::get_customer($job_data['customer_id']);
            if (!$current_user_id) {
                if ($job_data['customer_id'] && $customer['primary_user_id']) {
                    $current_user_id = $customer['primary_user_id'];
                }
            }
            $result = array();
            // adding a new note.
            $job_discussion_id = update_insert('job_discussion_id', 0, 'job_discussion', array('job_id' => $job_id, 'task_id' => $task_id, 'user_id' => $current_user_id, 'note' => $_POST['note']));
            $result['job_discussion_id'] = $job_discussion_id;
            $result['count'] = count($comments) + 1;
            $tasks = module_job::get_tasks($job_id);
            $result['email_customer'] = array();
            if (isset($_POST['sendemail_customer']) && is_array($_POST['sendemail_customer'])) {
                //$_POST['sendemail_customer'] == 'yes' && $customer['primary_user_id']){
                // send email to customer primary user id.
                $customer_contacts = module_user::get_contacts(array('customer_id' => $job_data['customer_id']));
                foreach ($_POST['sendemail_customer'] as $user_id) {
                    $user_id = (int) $user_id;
                    if ($user_id && isset($customer_contacts[$user_id])) {
                        // we can email this user.
                        $user = module_user::get_user($user_id, false);
                        if ($user && $user['user_id'] == $user_id) {
                            $values = array_merge($user, $job_data);
                            $values['job_url'] = module_job::link_public($job_id);
                            $values['job_url'] .= (strpos($values['job_url'], '?') === false ? '?' : '&') . 'discuss=' . $task_id . '#discuss' . $task_id;
                            $values['job_name'] = $job_data['name'];
                            $values['customer_name'] = $user['name'] . ' ' . $user['last_name'];
                            $values['note'] = $_POST['note'];
                            //todo: no order if no showning numbers
                            $values['task_name'] = '#' . $tasks[$task_id]['task_order'] . ': ' . $tasks[$task_id]['description'];
                            $template = module_template::get_template_by_key('job_discussion_email_customer');
                            $template->assign_values($values);
                            $html = $template->render('html');
                            $email = module_email::new_email();
                            $email->replace_values = $values;
                            $email->set_to('user', $user['user_id']);
                            $email->set_from('user', $current_user_id);
                            $email->set_subject($template->description);
                            // do we send images inline?
                            $email->set_html($html);
                            if ($email->send()) {
                                // it worked successfully!!
                                $result['email_customer'][] = $user['user_id'];
                            } else {
                                /// log err?
                            }
                        }
                    }
                }
                /*$user = module_user::get_user($customer['primary_user_id'],false);
                                if($user['user_id'] == $customer['primary_user_id']){
                                    $values = array_merge($user,$job_data);
                                    $values['job_url'] = module_job::link_public($job_id);
                                    $values['job_url'] .= (strpos($values['job_url'],'?')===false ? '?' : '&').'discuss='.$task_id.'#discuss'.$task_id;
                                    $values['job_name'] = $job_data['name'];
                                    $values['customer_name'] = $user['name'].' '.$user['last_name'];
                                    $values['note'] = $_POST['note'];
                                    //todo: no order if no showning numbers
                                    $values['task_name'] = '#'.$tasks[$task_id]['task_order'].': '.$tasks[$task_id]['description'];
                
                                    $template = module_template::get_template_by_key('job_discussion_email_customer');
                                    $template->assign_values($values);
                                    $html = $template->render('html');
                
                                    $email = module_email::new_email();
                                    $email->replace_values = $values;
                                    $email->set_to('user',$user['user_id']);
                                    $email->set_from('user',$current_user_id);
                                    $email->set_subject($template->description);
                                    // do we send images inline?
                                    $email->set_html($html);
                
                                    if($email->send()){
                                        // it worked successfully!!
                                        $result['email_customer'] = 1;
                                    }else{
                                        /// log err?
                                        $result['email_customer'] = 0;
                                    }
                                }else{
                                    // log error?
                                    $result['email_customer'] = 0;
                                }*/
            }
            if (isset($_POST['sendemail_staff']) && is_array($_POST['sendemail_staff'])) {
                // == 'yes' && $job_data['user_id']
                // todo: handle the restul better when sending to multiple people
                $result['email_staff_list'] = $_POST['sendemail_staff'];
                foreach ($_POST['sendemail_staff'] as $staff_id) {
                    // send email to staff
                    $staff_id = (int) $staff_id;
                    if (!$staff_id) {
                        $result['nostaff'] = 1;
                        continue;
                    }
                    if (isset($task_data['user_id']) && $task_data['user_id'] == $staff_id || isset($job_data['user_id']) && $job_data['user_id'] == $staff_id) {
                        //$user = module_user::get_user($job_data['user_id'],false);
                        $user = module_user::get_user($staff_id, false);
                        if ($user['user_id'] == $staff_id) {
                            $values = array_merge($user, $job_data);
                            $values['job_url'] = module_job::link_public($job_id);
                            $values['job_url'] .= (strpos($values['job_url'], '?') === false ? '?' : '&') . 'discuss=' . $task_id . '#discuss' . $task_id;
                            $values['job_name'] = $job_data['name'];
                            $values['staff_name'] = $user['name'] . ' ' . $user['last_name'];
                            $values['note'] = $_POST['note'];
                            //todo: no order if no showning numbers
                            $values['task_name'] = '#' . $tasks[$task_id]['task_order'] . ': ' . $tasks[$task_id]['description'];
                            $template = module_template::get_template_by_key('job_discussion_email_staff');
                            $template->assign_values($values);
                            $html = $template->render('html');
                            $email = module_email::new_email();
                            $email->replace_values = $values;
                            $email->set_to('user', $staff_id);
                            $email->set_from('user', $current_user_id);
                            $email->set_subject($template->description);
                            // do we send images inline?
                            $email->set_html($html);
                            if ($email->send()) {
                                // it worked successfully!!
                                $result['email_staff'] = 1;
                            } else {
                                /// log err?
                                $result['email_staff'] = 0;
                            }
                        } else {
                            // log error?
                            $result['email_staff'] = 0;
                        }
                    }
                }
            }
            $x = 0;
            while ($x++ < 5 && ob_get_level()) {
                ob_end_clean();
            }
            header("Content-type: text/javascript", true);
            echo json_encode($result);
            exit;
        }
        $label = htmlspecialchars(module_config::c('job_discussion_button_label', 'Task Comments'));
        ?>

        <a href="<?php 
        echo self::link_public($job_id, $task_id);
        ?>
" id="discuss<?php 
        echo $task_id;
        ?>
" class="task_job_discussion <?php 
        echo $label ? 'with_text' : '';
        ?>
" title="<?php 
        _e('View Discussion');
        ?>
"><span><?php 
        echo count($comments) > 0 ? count($comments) : '';
        ?>
</span><?php 
        echo $label;
        ?>
</a>
            <div class="task_job_discussion_holder"<?php 
        echo isset($_REQUEST['discuss']) && $_REQUEST['discuss'] == $task_id ? ' style="display:block;"' : '';
        ?>
>
                <?php 
        if (isset($_REQUEST['discuss']) && $_REQUEST['discuss'] == $task_id) {
            $_REQUEST['t'] = $task_id;
            $_REQUEST['i'] = $job_id;
            $_REQUEST['hash'] = self::link_public($job_id, $task_id, true);
            self::external_hook('public');
        }
        ?>

            </div>
        <?php 
    }
Пример #10
0
        ?>

                <div style="border-top:1px dashed #CCCCCC; padding:3px; margin:3px 0;">
                    <?php 
        echo $note_text;
        ?>

                    <div style="font-size:10px; text-align:right; color:#CCCCCC;">From <?php 
        echo $item['create_user_id'] ? module_user::link_open($item['create_user_id'], true) : _l('Customer');
        ?>
 on <?php 
        echo print_date($item['date_created'], true);
        ?>

                        <?php 
        if (module_file::can_i('delete', 'File Comments') || $item['create_user_id'] == module_security::get_loggedin_id()) {
            ?>

                        <a href="#" onclick="if(confirm('<?php 
            echo _l('Really remove this comment?');
            ?>
')){$('#delete_file_comment_id').val('<?php 
            echo $item['file_comment_id'];
            ?>
'); $('#butt_save_note').click(); } return false;" style="color:#FF0000">x</a>
                        <?php 
        }
        ?>

                    </div>
                </div>
Пример #11
0
 public function mark_as_read()
 {
     if ($this->social_twitter_message_id && module_security::is_logged_in()) {
         $sql = "REPLACE INTO `" . _DB_PREFIX . "social_twitter_message_read` SET `social_twitter_message_id` = " . (int) $this->social_twitter_message_id . ", `user_id` = " . (int) module_security::get_loggedin_id() . ", read_time = " . (int) time();
         query($sql);
     }
 }
Пример #12
0
                ?>
"><i
								    class="fa fa-user"></i> <?php 
                _e('Edit Profile');
                ?>
</a> <br/>
						    <a href="#" onclick="return false;"><i
								    class="fa fa-calendar"></i> <?php 
                echo _l('%s %s%s of %s %s', _l(date('D')), date('j'), _l(date('S')), _l(date('F')), date('Y'));
                ?>

						    </a>
					    </div>
				    </div>
				    <?php 
                if (module_security::can_user(module_security::get_loggedin_id(), 'Show Quick Search')) {
                    if (module_config::c('global_search_focus', 1) == 1) {
                        module_form::set_default_field('ajax_search_text');
                    }
                    ?>

					    <!-- search form -->
					    <form action="<?php 
                    echo _BASE_HREF;
                    ?>
?p=search_results" method="post" class="sidebar-form">
						    <div class="input-group">
							    <input type="text" name="quick_search" class="form-control"
							           value="<?php 
                    echo isset($_REQUEST['quick_search']) ? htmlspecialchars($_REQUEST['quick_search']) : '';
                    ?>
Пример #13
0
 public static function get_secure_key()
 {
     // generate a secure key for all sensitive form submissions.
     $hash = module_config::c('secure_hash', 0);
     if (!$hash) {
         $hash = md5(microtime() . mt_rand(1, 4000) . __FILE__ . time());
         // not very secure. meh.
         module_config::save_config('secure_hash', $hash);
     }
     $hash = md5($hash . "secure for user " . module_security::get_loggedin_id() . " with name " . module_security::get_loggedin_name() . session_id());
     return $hash;
 }
Пример #14
0
                <?php 
        }
        ?>

                </tbody>
            </table>
                </div>
                <?php 
    }
    ?>

        </td>
        <td valign="top">

            <?php 
    if (class_exists('module_job', false) && module_security::can_user(module_security::get_loggedin_id(), 'Show Dashboard Todo List')) {
        ?>


            <?php 
        print_heading(array('title' => 'Todo List', 'type' => 'h3'));
        ?>

                <div class="content_box_wheader">

             <table class="tableclass tableclass_rows tableclass_full">
                <tbody>
                <?php 
        $todo_list = module_job::get_tasks_todo();
        $x = 0;
        if (!count($todo_list)) {
Пример #15
0
/*
 *  Module: webNpro Menu Editor v1.0
 *  Copyright: Kőrösi Zoltán | webNpro - hosting and design | http://webnpro.com | info@webnpro.com
 *  Contact / Feature request: info@webnpro.com (Hungarian / English)
 *  License: Please check CodeCanyon.net for license details.
 *  More license clarification available here:  http://codecanyon.net/wiki/support/legal-terms/licensing-terms/
 */
// Get the infos about the plugin from the plugin.info file
$info = parse_ini_file(dirname(__FILE__) . '/../plugin.info');
$plugin_full_name = $info['fullname'];
$plugin_name = $info['modulename'];
$plugin_id = $info['id'];
$plugin_ver = $info['version'];
// Check permissions
if (!module_webnpro_menu_editor::can_i('edit', 'webNpro Menu Editor Settings', 'Config') && module_security::get_loggedin_id() != '1') {
    redirect_browser(_BASE_HREF);
}
// Include the update class
require_once dirname(__FILE__) . '/../update/updateclass.php';
// Get license infos
$update = new update();
$license = $update->get_license_info();
unset($update);
// Header buttons
$header_buttons[] = array('url' => _BASE_HREF . '?m[0]=' . $plugin_name . '&p[0]=documentation', 'title' => _l('Read Documentation'));
// Settings
$settings = array(array('key' => $plugin_name . '_envato_license_number', 'default' => '', 'type' => 'text', 'description' => _l('Plugin License key'), 'size' => '100', 'help' => _l('Please copy your license key here. They called it purchase code on the envato marketplaces. For more information about your license keys location check <a href="http://webnpro.com/images/envato_purchase_code_help.png" target="_blank">this image (...CLICK HERE...)</a>.')));
// Print the heading with the header buttons
print_heading(array('type' => 'h2', 'main' => true, 'title' => _l($plugin_full_name) . ' v' . $plugin_ver, 'button' => $header_buttons));
// Print the setting form
Пример #16
0
$template->assign_values(array('user_name' => htmlspecialchars($_SESSION['_user_name']), 'system_name' => htmlspecialchars(module_config::s('admin_system_name'))));
$widget_sort_json = @json_decode(module_config::c('dash_widgets_sort_' . module_security::get_loggedin_id()), true);
if (!is_array($widget_sort_json)) {
    $widget_sort_json = array();
}
$widget_sort_order = array();
$widget_sort_page_order = 1;
foreach ($widget_sort_json as $id => $vals) {
    $bits = explode('|', $vals);
    if (count($bits) == 3) {
        $widget_sort_order[$bits[2]] = array('column' => $bits[0], 'column_number' => $bits[1], 'page_order' => $widget_sort_page_order++);
    }
}
$widget_sort_id = 1;
// then display the alerts list.
if (module_config::c('dashboard_new_layout', 1) && class_exists('module_dashboard', false) && module_security::can_user(module_security::get_loggedin_id(), 'Show Dashboard Alerts')) {
    ob_start();
    module_dashboard::output_dashboard_alerts(module_config::c('dashboard_alerts_ajax', 1));
    array_unshift($home_widgets, array('columns' => isset($widget_sort_order[$widget_sort_id]['column']) ? $widget_sort_order[$widget_sort_id]['column'] : 1, 'column_number' => isset($widget_sort_order[$widget_sort_id]['column_number']) ? $widget_sort_order[$widget_sort_id]['column_number'] : false, 'page_order' => isset($widget_sort_order[$widget_sort_id]['page_order']) ? $widget_sort_order[$widget_sort_id]['page_order'] : false, 'sort_id' => $widget_sort_id++, 'title' => _l('Alerts'), 'content' => ob_get_clean()));
}
array_unshift($home_widgets, array('columns' => isset($widget_sort_order[$widget_sort_id]['column']) ? $widget_sort_order[$widget_sort_id]['column'] : 1, 'column_number' => isset($widget_sort_order[$widget_sort_id]['column_number']) ? $widget_sort_order[$widget_sort_id]['column_number'] : false, 'page_order' => isset($widget_sort_order[$widget_sort_id]['page_order']) ? $widget_sort_order[$widget_sort_id]['page_order'] : false, 'sort_id' => $widget_sort_id++, 'title' => _l('Home Page'), 'content' => _DEMO_MODE ? strip_tags($template->replace_content()) : $template->replace_content()));
// now grab the widgets from the various modules and add those in:
$widget_columns_counter = array();
foreach ($home_widgets as $module_widgets) {
    if (isset($module_widgets['id']) || isset($module_widgets['sort_id'])) {
        $module_widgets = array($module_widgets);
    }
    foreach ($module_widgets as $module_widget) {
        if (isset($widget_sort_order[$widget_sort_id]['column'])) {
            $module_widget['columns'] = $widget_sort_order[$widget_sort_id]['column'];
        }
Пример #17
0
 public static function start_payment($invoice_id, $payment_amount, $invoice_payment_id, $user_id = false)
 {
     if ($invoice_id && $payment_amount && $invoice_payment_id) {
         // we are starting a payment via coinbase!
         // setup a pending payment and redirect to coinbase.
         $invoice_data = module_invoice::get_invoice($invoice_id);
         if (!$user_id) {
             $user_id = $invoice_data['user_id'];
         }
         if (!$user_id) {
             $user_id = isset($invoice_data['primary_user_id']) ? $invoice_data['primary_user_id'] : 0;
         }
         if (!$user_id) {
             $user_id = module_security::get_loggedin_id();
         }
         $user_data = module_user::get_user($user_id);
         if (!$user_data || !strpos($user_data['email'], '@')) {
             die('Please ensure your user account has a valid email address before paying with coinbase');
         }
         $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
         // we add the fee details to the invoice payment record so that the new invoice total can be calculated.
         $fee_percent = module_config::c('payment_method_coinbase_charge_percent', 0);
         $fee_amount = module_config::c('payment_method_coinbase_charge_amount', 0);
         $fee_description = module_config::c('payment_method_coinbase_charge_description', 'Coinbase Fee');
         $fee_total = 0;
         if ($fee_percent != 0 || $fee_amount != 0) {
             $fee_total = module_invoice::calculate_fee($invoice_id, $invoice_data, $payment_amount, array('percent' => $fee_percent, 'amount' => $fee_amount, 'description' => $fee_description));
             if ($fee_total != 0) {
                 // add this percent/amount to the invoice payment
                 $payment_amount = $payment_amount + $fee_total;
                 update_insert('invoice_payment_id', $invoice_payment_id, 'invoice_payment', array('fee_percent' => $fee_percent, 'fee_amount' => $fee_amount, 'fee_description' => $fee_description, 'fee_total' => $fee_total, 'amount' => $payment_amount));
             }
         }
         // we check if this payment is a recurring payment or a standard one off payment.
         if (module_config::c('payment_method_coinbase_subscriptions', 0)) {
             // we support subscriptions!
             // first check if the subscription module is active, and if this invoice is part of an active subscription.
             $is_subscription = false;
             if (class_exists('module_subscription', false)) {
                 $subscription_history = get_single('subscription_history', 'invoice_id', $invoice_id);
                 if ($subscription_history && $subscription_history['subscription_id']) {
                     // this invoice is for a subscription! woo!
                     // work out when we should bill for this subscription.
                     $subscription = module_subscription::get_subscription($subscription_history['subscription_id']);
                     $subscription_owner = module_subscription::get_subscription_owner($subscription_history['subscription_owner_id']);
                     if ($subscription_owner['owner_table'] && $subscription_owner['owner_id']) {
                         // work out when the next invoice will be generated for this subscription.
                         $members_subscriptions = module_subscription::get_subscriptions_by($subscription_owner['owner_table'], $subscription_owner['owner_id']);
                         if (isset($members_subscriptions[$subscription_history['subscription_id']])) {
                             $member_subscription = $members_subscriptions[$subscription_history['subscription_id']];
                             // everything checks out! good to go....
                             // for now we just do a basic "EVERY X TIME" subscription
                             // todo: work out how long until next generate date, and set that (possibly smaller) time period as the first portion of the subscription
                             /*echo '<pre>';
                               print_r($subscription_history);
                               print_r($subscription);
                               print_r($subscription_owner);
                               print_r($member_subscription);
                               exit;*/
                             $is_subscription = array();
                             if ($subscription['days'] > 0) {
                                 $is_subscription['days'] = $subscription['days'];
                             }
                             if ($subscription['months'] > 0) {
                                 $is_subscription['months'] = $subscription['months'];
                             }
                             if ($subscription['years'] > 0) {
                                 $is_subscription['years'] = $subscription['years'];
                             }
                             if (count($is_subscription)) {
                                 $is_subscription['name'] = $subscription['name'];
                                 $is_subscription['id'] = $subscription_history['subscription_id'];
                             }
                         }
                     }
                 }
             }
             // todo: check if this invoice has a manual renewal date, perform subscription feature as above.
             if ($is_subscription) {
                 // coinbase only supports these recurring methods:
                 // daily, weekly, every_two_weeks, monthly, quarterly, and yearly
                 // work out which one our days are at.
                 $days = isset($is_subscription['days']) ? $is_subscription['days'] : 0;
                 if (isset($is_subscription['months'])) {
                     $days += $is_subscription['months'] * 30;
                     unset($is_subscription['months']);
                 }
                 if (isset($is_subscription['years'])) {
                     $days += $is_subscription['years'] * 365;
                     unset($is_subscription['years']);
                 }
                 $is_subscription['days'] = $days;
                 if ($days == 1) {
                     $is_subscription['coinbase_period'] = 'daily';
                 } else {
                     if ($days == 7 || $days == 6 || $days == 8) {
                         $is_subscription['coinbase_period'] = 'weekly';
                     } else {
                         if ($days == 14 || $days == 13 || $days == 15) {
                             $is_subscription['coinbase_period'] = 'every_two_weeks';
                         } else {
                             if ($days == 29 || $days == 30 || $days == 31) {
                                 $is_subscription['coinbase_period'] = 'monthly';
                             } else {
                                 if ($days >= 87 && $days <= 95) {
                                     $is_subscription['coinbase_period'] = 'quarterly';
                                 } else {
                                     if ($days >= 363 && $days <= 370) {
                                         $is_subscription['coinbase_period'] = 'yearly';
                                     } else {
                                         send_error('Someone tried to pay with coinbase but coinbase does not support a recurring subscription period of ' . $days . ' days. Only:  daily, weekly, every_two_weeks, monthly, quarterly, and yearly ');
                                         $is_subscription = false;
                                         // not supported.
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             if ($is_subscription && isset($is_subscription['coinbase_period'])) {
                 $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
                 if (isset($invoice_payment_data['invoice_payment_subscription_id']) && (int) $invoice_payment_data['invoice_payment_subscription_id'] > 0) {
                     // existing subscription already!
                     // not really sure what to do here, just redirect to coinbase as if the user is doing it for the first time.
                     $_REQUEST['payment_subscription'] = true;
                     // hacks!
                 }
                 if (isset($_REQUEST['payment_subscription']) || module_config::c('payment_method_coinbase_force_subscription', 0)) {
                     // user is setting up a subscription! yes!!
                     // we create an entry in our database for this particular subscription
                     // or if one exists for this payment already then we just continue with that (ie: the user is going in again to redo it)
                     // setup a new subscription in the database for us.
                     if (isset($invoice_payment_data['invoice_payment_subscription_id']) && (int) $invoice_payment_data['invoice_payment_subscription_id'] > 0) {
                         $invoice_payment_subscription_id = $invoice_payment_data['invoice_payment_subscription_id'];
                     } else {
                         $invoice_payment_subscription_id = update_insert('invoice_payment_subscription_id', false, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_PENDING, 'days' => isset($is_subscription['days']) ? $is_subscription['days'] : 0, 'months' => isset($is_subscription['months']) ? $is_subscription['months'] : 0, 'years' => isset($is_subscription['years']) ? $is_subscription['years'] : 0, 'date_start' => '0000-00-00', 'date_last_pay' => '0000-00-00', 'date_next' => '0000-00-00'));
                         update_insert('invoice_payment_id', $invoice_payment_id, 'invoice_payment', array('invoice_payment_subscription_id' => $invoice_payment_subscription_id));
                     }
                     $description = _l('Recurring payment for %s %s', $is_subscription['name'], _l(str_replace('_', ' ', $is_subscription['coinbase_period'])));
                     $subscription_name = $is_subscription['name'];
                     unset($is_subscription['name']);
                     // so reset/key cals below rosk.
                     $subscription_id = $is_subscription['id'];
                     unset($is_subscription['id']);
                     // so reset/key cals below rosk.
                     $currency = module_config::get_currency($invoice_payment_data['currency_id']);
                     $currency_code = $currency['code'];
                     include module_theme::include_ucm('includes/plugin_paymethod_coinbase/pages/coinbase_form.php');
                     exit;
                 } else {
                     if (isset($_REQUEST['payment_single'])) {
                         // use is choosing to continue payment as a once off amount
                     } else {
                         // give the user an option
                         $template = module_template::get_template_by_key('invoice_payment_subscription');
                         $template->page_title = htmlspecialchars($invoice_data['name']);
                         $template->assign_values($invoice_payment_data);
                         $template->assign_values(module_invoice::get_replace_fields($invoice_data['invoice_id'], $invoice_data));
                         $template->assign_values(array('invoice_payment_id' => $invoice_payment_id, 'payment_url' => module_invoice::link_public_pay($invoice_data['invoice_id']), 'payment_method' => 'paymethod_coinbase', 'payment_amount' => $payment_amount, 'pretty_payment_amount' => dollar($payment_amount, true, $invoice_data['currency_id']), 'subscription_period' => _l('%s days (%s)', $is_subscription['days'], $is_subscription['coinbase_period']), 'fee_amount' => dollar($fee_amount, true, $invoice_data['currency_id']), 'fee_total' => dollar($fee_total, true, $invoice_data['currency_id']), 'fee_percent' => $fee_percent, 'fee_description' => $fee_description));
                         echo $template->render('pretty_html');
                         exit;
                     }
                 }
             }
         }
         $description = _l('Payment for invoice %s', $invoice_data['name']);
         //self::coinbase_redirect($description,$payment_amount,$user_id,$invoice_payment_id,$invoice_id,$invoice_payment_data['currency_id']);
         $currency = module_config::get_currency($invoice_payment_data['currency_id']);
         $currency_code = $currency['code'];
         include module_theme::include_ucm('includes/plugin_paymethod_coinbase/pages/coinbase_form.php');
         /*$template = new module_template();
           ob_start();
           $template->content = ob_get_clean();
           echo $template->render('pretty_html');*/
         exit;
     }
     return false;
 }
Пример #18
0
    public function external_hook($hook)
    {
        switch ($hook) {
            case 'popup':
                // popup not used any more. cross domain issues.
                // load up the full script to be injected into our clients website.
                $website_id = isset($_REQUEST['i']) ? (int) $_REQUEST['i'] : false;
                $change_request_id = $change_id = isset($_REQUEST['change_id']) ? (int) $_REQUEST['change_id'] : false;
                $hash = isset($_REQUEST['hash']) ? $_REQUEST['hash'] : false;
                $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : false;
                if ($type == 'popupjs') {
                    @ob_end_clean();
                    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                    header("Cache-Control: no-cache");
                    header("Pragma: no-cache");
                    header("Content-type: text/javascript");
                }
                if ($website_id && $hash && module_change_request::link_popup($website_id, true) == $hash) {
                    $change_history = module_change_request::get_remaining_changes($website_id);
                    $step = isset($_REQUEST['step']) ? (int) $_REQUEST['step'] : 0;
                    // get the change details out
                    if ($change_request_id) {
                        $change_request = module_change_request::get_change_request_by_website($website_id, $change_request_id);
                    } else {
                        $change_request = array();
                    }
                    if (!$change_request) {
                        $change_request = array('change_request_id' => 0, 'name' => '', 'request' => '', 'attachments' => array());
                    }
                    switch ($type) {
                        case 'save':
                            // saving a change.
                            $data = $_POST;
                            $data['url'] = urldecode($data['url']);
                            $data['website_id'] = $website_id;
                            $data['change_request_id'] = $change_request['change_request_id'];
                            if (isset($_REQUEST['completed_test'])) {
                                if (!isset($_REQUEST['completed']) || !$_REQUEST['completed']) {
                                    $data['status'] = _CHANGE_REQUEST_STATUS_NEW;
                                    // not completed.
                                } else {
                                    $data['status'] = _CHANGE_REQUEST_STATUS_COMPLETE;
                                    // completed!
                                }
                            }
                            if (isset($_REQUEST['delete_request'])) {
                                $data['status'] = _CHANGE_REQUEST_STATUS_DELETE;
                                // deleted
                            }
                            $change_request_id = update_insert('change_request_id', $change_request['change_request_id'], 'change_request', $data);
                            // redirect to send email page if we're logged in
                            if (module_security::is_logged_in() && isset($_REQUEST['completed_send_email']) && $_REQUEST['completed_send_email'] && self::can_i('edit', 'Change Requests')) {
                                // don't do the template, do the redirect to the email page (todo!)
                                redirect_browser(self::link_open($change_request_id));
                            } else {
                                // send email to administrator (everyone with change request edit permissions?) about this change request.
                                $alert_users = module_user::get_users_by_permission(array('category' => 'Change Request', 'name' => 'Change Requests', 'module' => 'change_request', 'edit' => 1));
                                $email_data = get_single('change_request', 'change_request_id', $change_request_id);
                                $customer_data = $website_data = array();
                                if ($website_id) {
                                    $website_data = module_website::get_website($website_id);
                                    $email_data['website_name'] = $website_data['name'];
                                    $email_data['website_link'] = module_website::link_open($website_id, true);
                                    if ($website_data && $website_data['customer_id']) {
                                        $customer_data = module_customer::get_customer($website_data['customer_id'], true);
                                    }
                                }
                                if (isset($email_data['request'])) {
                                    $email_data['request'] = nl2br($email_data['request']);
                                    // for the plain text emails.
                                }
                                foreach ($alert_users as $alert_user) {
                                    // todo: make sure this staff member has access to this website?
                                    // nfi how to figure this out. maybe we just look for staff members who are assigned jobs/tasks against this website?
                                    $template = module_template::get_template_by_key('change_request_alert_email');
                                    $template->assign_values(array_merge($customer_data, $website_data, $email_data));
                                    $html = $template->render('html');
                                    // send an email to this user.
                                    $email = module_email::new_email();
                                    $email->replace_values = array_merge($customer_data, $website_data, $email_data);
                                    $email->set_to('user', $alert_user['user_id']);
                                    $email->set_from('user', module_security::get_loggedin_id() ? module_security::get_loggedin_id() : isset($customer_data['primary_user_id']) ? $customer_data['primary_user_id'] : 0);
                                    $email->set_subject($template->description);
                                    // do we send images inline?
                                    $email->set_html($html);
                                    if ($email->send()) {
                                        // it worked successfully!!
                                        // sweet.
                                    } else {
                                        /// log err?
                                        set_error(_l('Failed to send change notification email to User ID: %s Email: %s Status: %s Error: %s', $alert_user['user_id'], json_encode($email->to), $email->status, $email->error_text));
                                    }
                                }
                            }
                            // display thankyou template.
                            module_template::init_template('change_request_submitted', '<h2>Change Request</h2>
    <p>Thank you. Your change request has been submitted successfully.</p>
    <p>Please <a href="{URL}">click here</a> to continue.</p>
    ', 'Displayed after a change request is created/updated.', 'code');
                            // correct!
                            // load up the receipt template.
                            $template = module_template::get_template_by_key('change_request_submitted');
                            $template->page_title = _l("Change Request");
                            foreach ($data as $key => $val) {
                                if (!is_array($val)) {
                                    $data[$key] = htmlspecialchars($val);
                                }
                            }
                            $template->assign_values($data);
                            echo $template->render('pretty_html');
                            exit;
                            break;
                        case 'display_change':
                            ob_start();
                            ?>

                            <div class="title">
                                <?php 
                            _e('Change request');
                            ?>

                            </div>
                            <div class="content">
                                <p><?php 
                            echo nl2br(htmlspecialchars($change_request['request']));
                            ?>
</p>
                                <div class="wp3changerequest_actions">
                                    <p>
                                       <!-- <strong><?php 
                            _e('Attachments:');
                            ?>
</strong>
                                        <?php 
                            if (!$change_request['attachments']) {
                                ?>
 - none - <?php 
                            } else {
                                foreach ($change_request['attachments'] as $attachment) {
                                    ?>

                                            <a href="#"><?php 
                                    echo htmlspecialchars($attachment->name);
                                    ?>
</a>
                                            <?php 
                                }
                                ?>

                                        <?php 
                            }
                            ?>

                                        <br/>-->
                                        <strong><?php 
                            _e('Created by:');
                            ?>
</strong> <?php 
                            echo htmlspecialchars($change_request['name']);
                            ?>
 <br/>
                                        <strong><?php 
                            _e('Created on:');
                            ?>
</strong> <?php 
                            echo print_date($change_request['date_created'], true);
                            ?>

	                                    <?php 
                            if (isset($change_request['job_id']) && $change_request['job_id']) {
                                ?>
 <br/>
		                                    <strong><?php 
                                _e('Converted to job:');
                                ?>
</strong> <?php 
                                _e('This task has been converted to a Job');
                                ?>

	                                    <?php 
                            }
                            ?>

                                    </p>
                                    <?php 
                            if (!isset($change_request['job_id']) || !$change_request['job_id'] || self::can_i('edit', 'Change Requests')) {
                                ?>

                                    <p align="center">
                                        <input type="button" name="edit" value="<?php 
                                _e('Edit');
                                ?>
" class="wp3changerequest_button wp3changerequest_button_small"  onclick="dtbaker_changerequest.edit(<?php 
                                echo $change_request_id;
                                ?>
); return false;">
                                    </p>
	                                <?php 
                            }
                            ?>

                                </div>
                            </div>
                            <?php 
                            $change_request['html'] = preg_replace('/\\s+/', ' ', ob_get_clean());
                            //                                echo json_encode($change_request);
                            //                                exit;
                            @ob_end_clean();
                            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                            header("Cache-Control: no-cache");
                            header("Pragma: no-cache");
                            header("Content-type: text/javascript");
                            ?>


                            var t = dtbaker_changerequest;
                            var change_id = <?php 
                            echo $change_request_id;
                            ?>
;
                                var msg = <?php 
                            echo json_encode($change_request);
                            ?>
;

                            jQuery('body').prepend('<div class="wp3changerequest_change" id="dtbaker_change_'+change_id+'" style="'+((!t.show_postits) ? 'display:none;':'')+'"></div>');
                            var box = jQuery('#dtbaker_change_'+change_id);
                            box.html(msg.html);
                            if(msg.status == 0){
                                box.addClass('wp3changerequest_change_pending');
                            }else if(msg.status == 2){
                                box.addClass('wp3changerequest_change_complete');
                            }else if(msg.status == 3){
                                box.addClass('wp3changerequest_change_deleted');
                            }
                            box.css('top',msg.y+'px');
                            box.data('window_width',msg.window_width);
                            box.data('left',msg.x);
                            t.set_left(change_id);
                            with({i:change_id}){
                                jQuery(window).resize(function () {
                                    t.set_left(i);
                                });
                            }
                            box.data('original_height',box.height());
                            box.css('overflow','hidden');
                            jQuery('.title',box).slideUp();
                            box.stop(true, true).animate({
                                height: t.min_height,
                                width: t.min_width
                            },500);
                            box.hover(function(){
                                jQuery(this).addClass('wp3changerequest_change_active');
                                jQuery('.title',this).stop(true, true).slideDown();
                                jQuery(this).stop().animate({
                                    width: t.max_width,
                                    height: jQuery(this).data('original_height'),
                                    opacity: 1
                                },500);
                            },function(){
                                jQuery('.title',this).stop(true, true).slideUp();
                                jQuery(this).stop().animate({
                                    width: t.min_width,
                                    height: t.min_height,
                                    opacity: 0.7
                                },500,function(){
                                    jQuery(this).removeClass('wp3changerequest_change_active');
                                });
                            })


                                <?php 
                            break;
                        default:
                            @ob_end_clean();
                            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                            header("Cache-Control: no-cache");
                            header("Pragma: no-cache");
                            header("Content-type: text/javascript");
                            ob_start();
                            include 'pages/popup.php';
                            $html = ob_get_clean();
                            $html = addcslashes($html, "'");
                            $html = preg_replace('#\\r|\\n#', "' +\n'", $html);
                            // inject using javascript. fixes cross domain issues
                            ?>

                            if(!jQuery('#dtbaker_changerequest_inlinewizard').length){
                                // fix for jQuery 1.9+
                                jQuery('body').append('<div id="dtbaker_changerequest_inlinewizard" style="display:none;"></div>');
                            }
                            jQuery('#dtbaker_changerequest_inlinewizard').html('<?php 
                            echo $html;
                            ?>
');
                            <?php 
                    }
                }
                exit;
                break;
            case 'script':
                // load up the full script to be injected into our clients website.
                $website_id = isset($_REQUEST['i']) ? (int) $_REQUEST['i'] : false;
                $hash = isset($_REQUEST['hash']) ? $_REQUEST['hash'] : false;
                @ob_end_clean();
                header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                header("Cache-Control: no-cache");
                header("Pragma: no-cache");
                header("Content-type: text/javascript");
                if ($website_id && $hash && module_change_request::link_script($website_id, true) == $hash) {
                    include "js/client.js";
                    $client_url = isset($_REQUEST['url']) ? $_REQUEST['url'] : false;
                    if ($client_url) {
                        $change_requests = self::get_change_requests(array('website_id' => $website_id, 'url' => $client_url));
                        // todo - option this out incase url causes issues. ie: old js check method
                        ?>

                        jQuery(function(){
                            <?php 
                        foreach ($change_requests as $change_request) {
                            $displayed = false;
                            if ($change_request['status'] == _CHANGE_REQUEST_STATUS_NEW) {
                                $displayed = true;
                                ?>

                                    dtbaker_changerequest.display_change(<?php 
                                echo $change_request['change_request_id'];
                                ?>
);
                            <?php 
                            }
                            if (isset($_SESSION['_change_request_highlight']) && $_SESSION['_change_request_highlight'] == $change_request['change_request_id']) {
                                ?>

                                    <?php 
                                if (!$displayed) {
                                    ?>

                                    dtbaker_changerequest.display_change(<?php 
                                    echo $change_request['change_request_id'];
                                    ?>
);
                                    <?php 
                                }
                                ?>

                                    dtbaker_changerequest.highlight(<?php 
                                echo (int) $_SESSION['_change_request_highlight'];
                                ?>
);
                                    <?php 
                                unset($_SESSION['_change_request_highlight']);
                            }
                        }
                        ?>

                        });
                        <?php 
                    } else {
                        // not posting the URL, some setups do not like this
                        // get list of active change requests
                        $change_requests = self::get_change_requests(array('website_id' => $website_id, 'status' => _CHANGE_REQUEST_STATUS_NEW));
                        // we also do completed ones because the change request highlight countbe in there
                        $completed_change_requests = self::get_change_requests(array('website_id' => $website_id, 'status' => _CHANGE_REQUEST_STATUS_COMPLETE));
                        ?>


                        jQuery(function(){
                            var current_url = window.location.href;
                            <?php 
                        foreach ($change_requests as $change_request) {
                            ?>

                            if(current_url == '<?php 
                            echo addcslashes(htmlspecialchars($change_request['url']), "'");
                            ?>
'){
                                // todo: do this better!
                                dtbaker_changerequest.display_change(<?php 
                            echo $change_request['change_request_id'];
                            ?>
);
                            }
                            <?php 
                        }
                        ?>

                            <?php 
                        // todo: do we display all previous change requests on the page or not?
                        if (isset($_SESSION['_change_request_highlight']) && $_SESSION['_change_request_highlight']) {
                            echo '// Checking for request: ' . (int) $_SESSION['_change_request_highlight'];
                            foreach ($completed_change_requests as $complete_change_request) {
                                if ($complete_change_request['change_request_id'] == $_SESSION['_change_request_highlight']) {
                                    // show this completed one as well.
                                    ?>

                                        dtbaker_changerequest.display_change(<?php 
                                    echo $complete_change_request['change_request_id'];
                                    ?>
);
                                        <?php 
                                }
                            }
                            ?>

                            dtbaker_changerequest.highlight(<?php 
                            echo (int) $_SESSION['_change_request_highlight'];
                            ?>
);
                            <?php 
                            // todo: move this unset over to the "display_change" callback so we only remove the session when we know it has been displayed.
                            unset($_SESSION['_change_request_highlight']);
                        }
                        ?>

                        });
                        <?php 
                    }
                }
                exit;
                break;
            case 'public':
                $website_id = isset($_REQUEST['i']) ? (int) $_REQUEST['i'] : false;
                $hash = isset($_REQUEST['hash']) ? $_REQUEST['hash'] : false;
                if ($website_id && $hash && module_change_request::link_public($website_id, true) == $hash) {
                    // correct!
                    // redirect to website with our "change_request" url parameter, that is picked up by the included text.
                    $website = module_website::get_website($website_id);
                    $change_request_website = get_single('change_request_website', 'website_id', $website_id);
                    if ($change_request_website && $change_request_website['enabled']) {
                        $url = module_website::urlify($website['url']);
                        // todo - pass this to a (yet to be created) method in website that will deal with https:// or http:// based on user input. stop hardcoding http!
                        if (isset($_REQUEST['change_request_id'])) {
                            $selected_change_request = self::get_change_request_by_website($website_id, (int) $_REQUEST['change_request_id']);
                            if ($selected_change_request && $selected_change_request['url']) {
                                $url = $selected_change_request['url'];
                            }
                            //$url .= "&change_request_id=".(int)$_REQUEST['change_request_id'];
                            $_SESSION['_change_request_highlight'] = (int) $_REQUEST['change_request_id'];
                        }
                        $url = $url . (strpos($url, '?') === false ? '?' : '&') . 'change_request=' . self::link_script($website_id, true);
                        redirect_browser($url);
                    }
                }
                echo "Change request disabled.";
                break;
        }
    }
Пример #19
0
        $data_record_revisions = $module->get_data_record_revisions($data_record_id);
        $revision_count = count($data_record_revisions);
        /*if(getlevel()!="administrator" && $data_record['create_user_id'] != $_SESSION['_user_id']){
        			// dodgy security check. but works.
        			echo 'Sorry, you do not have permission to access this record';
        			exit;
        		}*/
        // record that a record was accessed
        $module->record_access($data_record_id);
    } else {
        // for printing otu the summary:
        $data_record['status'] = 'New';
        $data_record['data_record_id'] = $module->next_record_id();
        $data_record['create_ip_address'] = $_SERVER['REMOTE_ADDR'];
        $data_record['update_ip_address'] = '';
        $data_record['create_user_id'] = module_security::get_loggedin_id();
        $data_record['date_created'] = time();
        $data_record['date_updated'] = false;
        $data_record['parent_data_record_id'] = isset($_REQUEST['parent_data_record_id']) ? (int) $_REQUEST['parent_data_record_id'] : 0;
        $update_user = $create_user = module_user::get_user($data_record['create_user_id']);
        $data_record_revisions = array();
        $data_record_revision_id = false;
        $revision_count = 0;
        $data_items = array();
    }
}
if (!isset($data_type_id) || !$data_type_id) {
    $data_type_id = isset($_REQUEST['data_type_id']) ? (int) $_REQUEST['data_type_id'] : false;
}
if (!isset($data_type) || !$data_type) {
    if ($data_type_id) {
Пример #20
0
 public static function write($session_id, $data)
 {
     if (self::$destroyed) {
         return false;
     }
     if (self::$session_hash && md5($data) == self::$session_hash) {
         return true;
     }
     // session data hasn't changed, dont re-write it
     if (!self::db_table_exists('session', true)) {
         return file_put_contents(_UCM_FOLDER . "/temp/sess_{$session_id}", $data) === false ? false : true;
     }
     /*if(function_exists('mb_detect_encoding') && mb_detect_encoding($data)!='ASCII'){
           $data = '!'.mb_detect_encoding($data).'!'.$data;
       }*/
     try {
         $user_id = module_security::get_loggedin_id();
         $logged_in = module_security::is_logged_in();
         // are we creating or reading?
         $sql = "SELECT session_id FROM `" . _DB_PREFIX . "session` WHERE `session_id` = '" . mysql_real_escape_string(self::$session_id) . "'";
         $res = query($sql);
         if (mysql_num_rows($res) > 0) {
             // we have a session! woo!
             // update existing
             $data = base64_encode($data);
             $sql = "UPDATE `" . _DB_PREFIX . "session` SET ";
             $sql .= " `last_access` = " . (int) time() . ", `session_data` = '" . mysql_real_escape_string($data) . "', `logged_in` = " . (int) $logged_in . ", ip_address = '" . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . "' ";
             if ($logged_in) {
                 // only write the user id if we're logged in
                 // this keeps user id active for closed user sessions
                 $sql .= ", `user_id` = " . (int) $user_id . " ";
             }
             $sql .= " WHERE `session_id` = '" . mysql_real_escape_string($session_id) . "'";
             query($sql);
         } else {
             // create new! only difference is set set a created timestamo
             $sql = "INSERT INTO `" . _DB_PREFIX . "session` SET `created` = " . (int) time() . ",`last_access` = " . (int) time() . ", `session_data` = '" . mysql_real_escape_string($data) . "', `user_id` = " . (int) $user_id . ", `logged_in` = " . (int) $logged_in . ", ip_address = '" . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . "', `session_id` = '" . mysql_real_escape_string($session_id) . "'";
             query($sql);
         }
     } catch (Exception $e) {
         echo $e->getMessage();
     }
     return true;
 }
Пример #21
0
    </div>
    <textarea rows="4" cols="30" name="new_comment"></textarea> <br/>
    <input type="button" name="add" value="<?php 
    _e('Add Comment');
    ?>
" class="task_job_discussion_add small_button" data-jobid="<?php 
    echo $job_id;
    ?>
" data-taskid="<?php 
    echo $task_id;
    ?>
">
    <?php 
    $send_to_customer_ids = array();
    $send_to_staff_ids = array();
    if (module_security::get_loggedin_id() && $job_data['customer_id'] && $customer['primary_user_id'] && $customer['primary_user_id'] != $current_user_id) {
        $send_to_customer_ids[$customer['primary_user_id']] = 1;
        // put the other customer contacts in here too.
        $customer_contacts = module_user::get_contacts(array('customer_id' => $job_data['customer_id']));
        foreach ($customer_contacts as $contact) {
            $send_to_customer_ids[$contact['user_id']] = 1;
        }
    }
    if ($job_data['user_id'] && $job_data['user_id'] != $current_user_id && $job_data['user_id'] != $customer['primary_user_id']) {
        $send_to_staff_ids[$job_data['user_id']] = module_config::c('job_discussion_staff_checked', 1);
    }
    if ($task_data['user_id'] && $task_data['user_id'] != $current_user_id && $task_data['user_id'] != $customer['primary_user_id']) {
        $send_to_staff_ids[$task_data['user_id']] = module_config::c('job_discussion_staff_checked', 1);
    }
    if (!module_security::is_logged_in()) {
        echo '<div style="display:none;">';
Пример #22
0
 public static function get_job_task_access_permissions()
 {
     if (class_exists('module_security', false)) {
         return module_security::can_user_with_options(module_security::get_loggedin_id(), 'Job Task Data Access', array(_JOB_TASK_ACCESS_ALL, _JOB_TASK_ACCESS_ASSIGNED_ONLY));
     } else {
         return _JOB_TASK_ACCESS_ALL;
         // default to all permissions.
     }
 }
Пример #23
0
 public static function get_invoice($invoice_id, $basic = false, $skip_permissions = false)
 {
     $invoice = array();
     $invoice_id = (int) $invoice_id;
     if ((int) $invoice_id > 0) {
         // we check the cache to see if the 'full' copy of this invoice exists anywhere yet.
         // if it does
         $cache_key = self::_invoice_cache_key($invoice_id, array($invoice_id, $basic, $skip_permissions, isset($_REQUEST['customer_id']) ? $_REQUEST['customer_id'] : 0, isset($_REQUEST['job_id']) ? $_REQUEST['job_id'] : 0));
         if ($cached_item = module_cache::get('invoice', $cache_key)) {
             return $cached_item;
         }
         $cache_key_full = self::_invoice_cache_key($invoice_id, array($invoice_id, false, $skip_permissions, isset($_REQUEST['customer_id']) ? $_REQUEST['customer_id'] : 0, isset($_REQUEST['job_id']) ? $_REQUEST['job_id'] : 0));
         if ($cache_key_full != $cache_key && ($cached_item = module_cache::get('invoice', $cache_key_full))) {
             return $cached_item;
         }
         $cache_timeout = module_config::c('cache_objects', 60);
         if ($basic === 2) {
             // used in links. just want the invoice name really.
             // todo - cache. meh
             return get_single('invoice', 'invoice_id', $invoice_id);
         } else {
             $sql = "SELECT i.*";
             $sql .= ", c.primary_user_id  ";
             // AS user_id // DONE - change this to the invoice table. drop down to select invoice contact. auto select based on contacts role?
             $sql .= ", c.customer_name AS customer_name ";
             $sql .= ", GROUP_CONCAT(DISTINCT j.`website_id` SEPARATOR ',') AS website_ids";
             // the website id(s)
             $sql .= ", GROUP_CONCAT(DISTINCT j.`job_id` SEPARATOR ',') AS job_ids";
             // the job id(s)
             $sql .= ", j.customer_id AS new_customer_id ";
             $sql .= " FROM `" . _DB_PREFIX . "invoice` i ";
             $sql .= " LEFT JOIN `" . _DB_PREFIX . "invoice_item` ii USING (invoice_id) ";
             $sql .= " LEFT JOIN `" . _DB_PREFIX . "task` t ON ii.task_id = t.task_id";
             $sql .= " LEFT JOIN `" . _DB_PREFIX . "job` j ON t.job_id = j.job_id";
             $sql .= " LEFT JOIN `" . _DB_PREFIX . "customer` c ON i.customer_id = c.customer_id ";
             //$sql .= " LEFT JOIN `"._DB_PREFIX."user` u ON c.primary_user_id = u.user_id ";
             $sql .= " WHERE i.invoice_id = " . (int) $invoice_id;
             $sql .= " GROUP BY i.invoice_id";
             $invoice = qa1($sql);
             if (isset($invoice['website_id']) && $invoice['website_id']) {
                 $website_ids = explode(',', $invoice['website_ids']);
                 if (!in_array($invoice['website_id'], $website_ids)) {
                     $website_ids[] = $invoice['website_id'];
                     $invoice['website_ids'] = implode(',', $website_ids);
                 }
             }
         }
         if (isset($invoice['job_ids']) && strlen(trim($invoice['job_ids'])) > 0) {
             $invoice['job_ids'] = explode(',', $invoice['job_ids']);
         } else {
             $invoice['job_ids'] = array();
         }
         // check permissions
         if ($invoice && isset($invoice['invoice_id']) && $invoice['invoice_id'] == $invoice_id) {
             switch (self::get_invoice_access_permissions()) {
                 case _INVOICE_ACCESS_ALL:
                     break;
                 case _INVOICE_ACCESS_STAFF:
                     if ($invoice['vendor_user_id'] != module_security::get_loggedin_id()) {
                         if ($skip_permissions) {
                             $invoice['_no_access'] = true;
                             // set a flag for custom processing. we check for this when calling get_customer with the skip permissions argument. (eg: in the ticket file listing link)
                         } else {
                             $invoice = false;
                         }
                     }
                     break;
                 case _INVOICE_ACCESS_JOB:
                     // only invoices from jobs!
                     $has_invoice_access = false;
                     $jobs = module_job::get_jobs();
                     foreach ($invoice['job_ids'] as $invoice_job_id) {
                         if (isset($jobs[$invoice_job_id])) {
                             $has_invoice_access = true;
                         }
                     }
                     unset($jobs);
                     if (!$has_invoice_access) {
                         if ($skip_permissions) {
                             $invoice['_no_access'] = true;
                             // set a flag for custom processing. we check for this when calling get_customer with the skip permissions argument. (eg: in the ticket file listing link)
                         } else {
                             $invoice = false;
                         }
                     }
                     break;
                 case _INVOICE_ACCESS_CUSTOMER:
                     // tie in with customer permissions to only get invoices from customers we can access.
                     $customers = module_customer::get_customers();
                     $has_invoice_access = false;
                     if (isset($customers[$invoice['customer_id']])) {
                         $has_invoice_access = true;
                     }
                     unset($customers);
                     /*foreach($customers as $customer){
                           // todo, if($invoice['customer_id'] == 0) // ignore this permission
                           if($customer['customer_id']==$invoice['customer_id']){
                               $has_invoice_access = true;
                               break;
                           }
                       }*/
                     if (!$has_invoice_access) {
                         if ($skip_permissions) {
                             $invoice['_no_access'] = true;
                             // set a flag for custom processing. we check for this when calling get_customer with the skip permissions argument. (eg: in the ticket file listing link)
                         } else {
                             $invoice = false;
                         }
                     }
                     break;
             }
             //            print_r($invoice);exit;
             if (!$invoice) {
                 return array();
             }
             $original_invoice = $invoice;
             $invoice['taxes'] = get_multiple('invoice_tax', array('invoice_id' => $invoice_id), 'invoice_tax_id', 'exact', 'order');
             // set the job id of the first job just for kicks
             if (isset($invoice['deposit_job_id']) && (int) $invoice['deposit_job_id'] > 0) {
                 $invoice['job_ids'][] = $invoice['deposit_job_id'];
             }
             if (isset($invoice['website_ids'])) {
                 $invoice['website_ids'] = explode(',', $invoice['website_ids']);
             } else {
                 $invoice['website_ids'] = array();
             }
             // incase teh customer id on this invoice changes:
             if (isset($invoice['new_customer_id']) && $invoice['new_customer_id'] > 0 && $invoice['new_customer_id'] != $invoice['customer_id']) {
                 $invoice['customer_id'] = $invoice['new_customer_id'];
                 update_insert('invoice_id', $invoice_id, 'invoice', array('customer_id' => $invoice['new_customer_id']));
             }
             if ($invoice['customer_id'] > 0) {
                 $customer_data = module_customer::get_customer($invoice['customer_id']);
                 if ($customer_data && class_exists('module_company', false) && isset($invoice['company_id']) && !$invoice['company_id'] && isset($customer_data['company_ids']) && count($customer_data['company_ids']) == 1) {
                     // check if this customer has a company.
                     $invoice['company_id'] = key($customer_data['company_ids']);
                 }
             }
             if ($basic === true) {
                 module_cache::put('invoice', $cache_key, $invoice, $cache_timeout);
                 return $invoice;
             }
         }
     }
     // not sure why this code was here, commenting it out for now until we need it.
     /*if(isset($invoice['customer_id']) && isset($invoice['job_id']) && $invoice['customer_id'] <= 0 && $invoice['job_id'] > 0){
           $job_data = module_job::get_job($invoice['job_id'],false);
           $invoice['customer_id'] = $job_data['customer_id'];
       }*/
     if (!$invoice || !is_array($invoice) || !isset($invoice['invoice_id']) || !$invoice['invoice_id']) {
         $customer_id = isset($_REQUEST['customer_id']) ? $_REQUEST['customer_id'] : 0;
         $job_id = isset($_REQUEST['job_id']) ? $_REQUEST['job_id'] : 0;
         $currency_id = module_config::c('default_currency_id', 1);
         if ($customer_id > 0) {
             // find a default website to use ?
         } else {
             if ($job_id > 0) {
                 // only a job, no customer. set the customer id.
                 $job_data = module_job::get_job($job_id, false);
                 $customer_id = $job_data['customer_id'];
                 $currency_id = $job_data['currency_id'];
             }
         }
         // work out an invoice number
         $invoice_number = self::new_invoice_number($customer_id);
         $invoice = array('invoice_id' => 'new', 'customer_id' => $customer_id, 'job_id' => $job_id, 'job_ids' => $job_id > 0 ? array($job_id) : array(), 'currency_id' => $currency_id, 'name' => $invoice_number, 'cached_total' => 0, 'discount_description' => $job_id > 0 && isset($job_data['discount_description']) ? $job_data['discount_description'] : _l('Discount:'), 'discount_amount' => $job_id > 0 && isset($job_data['discount_amount']) ? $job_data['discount_amount'] : 0, 'discount_type' => $job_id > 0 && isset($job_data['discount_type']) ? $job_data['discount_type'] : module_config::c('invoice_discount_type', _DISCOUNT_TYPE_BEFORE_TAX), 'tax_type' => module_config::c('invoice_tax_type', 0), 'date_create' => date('Y-m-d'), 'date_sent' => '', 'date_due' => date('Y-m-d', strtotime('+' . module_config::c('invoice_due_days', 30) . ' days')), 'date_paid' => '', 'hourly_rate' => module_config::c('hourly_rate', 60), 'status' => module_config::s('invoice_status_default', 'New'), 'user_id' => '', 'date_renew' => '', 'renew_invoice_id' => '', 'deposit_job_id' => 0, 'date_cancel' => '0000-00-00', 'total_amount_deposits' => 0, 'total_amount_deposits_tax' => 0, 'default_task_type' => module_config::c('default_task_type', _TASK_TYPE_HOURS_AMOUNT), 'overdue_email_auto' => module_config::c('overdue_email_auto', 0), 'renew_auto' => 0, 'renew_email' => 0, 'overdue' => false, 'invoice_template_print' => '', 'website_id' => '0', 'website_ids' => '');
         $invoice['total_tax_rate'] = module_config::c('tax_percent', 10);
         $invoice['total_tax_name'] = module_config::c('tax_name', 'TAX');
         $customer_data = false;
         if ($customer_id > 0) {
             $customer_data = module_customer::get_customer($customer_id);
         }
         if ($customer_data && $customer_data['customer_id'] && $customer_data['customer_id'] == $customer_id) {
             // is there a default invoice template for this customer?
             if (class_exists('module_extra', false)) {
                 $extras = module_extra::get_extras(array('owner_table' => 'customer', 'owner_id' => $customer_id));
                 foreach ($extras as $e) {
                     if ($e['extra_key'] == 'invoice_template_print') {
                         $invoice['invoice_template_print'] = $e['extra'];
                     }
                 }
             }
             if ($customer_data['primary_user_id']) {
                 $invoice['primary_user_id'] = $customer_data['primary_user_id'];
             }
             if (isset($customer_data['default_tax']) && $customer_data['default_tax'] >= 0) {
                 $invoice['total_tax_rate'] = $customer_data['default_tax'];
                 $invoice['total_tax_name'] = $customer_data['default_tax_name'];
             }
         }
     }
     // drag some details from the related job
     $first_job_id = 0;
     if (!(int) $invoice_id) {
         if (isset($invoice['job_ids']) && $invoice['job_ids']) {
             $first_job_id = current($invoice['job_ids']);
         } else {
             if (isset($invoice['job_id']) && $invoice['job_id']) {
                 $first_job_id = $invoice['job_id'];
                 // abckwards compatibility
             } else {
                 $first_job_id = 0;
             }
         }
         if ($first_job_id > 0) {
             $job_data = module_job::get_job($first_job_id, false);
             $invoice['hourly_rate'] = $job_data['hourly_rate'];
             $invoice['taxes'] = $job_data['taxes'];
             //$invoice['total_tax_rate'] = $job_data['total_tax_rate'];
             //$invoice['total_tax_name'] = $job_data['total_tax_name'];
         }
     }
     // new support for multiple taxes
     if (!isset($invoice['taxes']) || !count($invoice['taxes']) && $invoice['total_tax_rate'] > 0) {
         $invoice['taxes'] = array();
         if ($first_job_id > 0 && !(int) $invoice_id) {
             // taxes set above from job
         } else {
             $tax_rates = explode(',', $invoice['total_tax_rate']);
             $tax_names = explode(',', $invoice['total_tax_name']);
             foreach ($tax_rates as $tax_rate_id => $tax_rate_amount) {
                 if ($tax_rate_amount > 0) {
                     $invoice['taxes'][] = array('order' => 0, 'percent' => $tax_rate_amount, 'name' => isset($tax_names[$tax_rate_id]) ? $tax_names[$tax_rate_id] : $invoice['total_tax_name'], 'total' => 0, 'amount' => 0, 'discount' => 0, 'increment' => module_config::c('tax_multiple_increment', 0));
                 }
             }
         }
     }
     // work out total hours etc..
     //$invoice['total_hours'] = 0;
     //$invoice['total_hours_completed'] = 0;
     //$invoice['total_hours_overworked'] = 0;
     $invoice['discount_amount_on_tax'] = 0;
     // used in job.php
     $invoice['total_sub_amount'] = 0;
     $invoice['total_sub_amount_taxable'] = 0;
     $invoice_items = self::get_invoice_items((int) $invoice['invoice_id'], $invoice);
     foreach ($invoice_items as $invoice_item) {
         if ($invoice_item['invoice_item_amount'] != 0) {
             // we have a custom amount for this invoice_item
             $invoice['total_sub_amount'] += $invoice_item['invoice_item_amount'];
             if ($invoice_item['taxable']) {
                 $invoice['total_sub_amount_taxable'] += $invoice_item['invoice_item_amount'];
                 if (module_config::c('tax_calculate_mode', _TAX_CALCULATE_AT_END) == _TAX_CALCULATE_INCREMENTAL) {
                     // tax calculated along the way (this isn't the recommended way, but was included as a feature request)
                     // we add tax to each of the tax array items
                     //$invoice['total_tax'] += round(($invoice_item['invoice_item_amount'] * ($invoice['total_tax_rate'] / 100)),module_config::c('currency_decimal_places',2));
                     foreach ($invoice['taxes'] as $invoice_tax_id => $invoice_tax) {
                         if (!isset($invoice['taxes'][$invoice_tax_id]['total'])) {
                             $invoice['taxes'][$invoice_tax_id]['total'] = 0;
                         }
                         $invoice['taxes'][$invoice_tax_id]['total'] += $invoice_item['invoice_item_amount'];
                         $invoice['taxes'][$invoice_tax_id]['amount'] += round($invoice_item['invoice_item_amount'] * ($invoice_tax['percent'] / 100), module_config::c('currency_decimal_places', 2));
                     }
                 }
             }
         }
     }
     //$invoice['final_modification'] = 0; // hack for discount modes - change this to just 'discount_amount' cos that is all that uses this variable. HERE
     // add any discounts.
     if ($invoice['discount_amount'] != 0) {
         if ($invoice['discount_type'] == _DISCOUNT_TYPE_AFTER_TAX) {
             // after tax discount ::::::::::
             // handled below.
             //$invoice['final_modification'] = -$invoice['discount_amount'];
         } else {
             if ($invoice['discount_type'] == _DISCOUNT_TYPE_BEFORE_TAX) {
                 // before tax discount:::::
                 //$invoice['final_modification'] = -$invoice['discount_amount'];
                 // problem : this 'discount_amount_on_tax' calculation may not match the correct final discount calculation as per below
                 if (module_config::c('tax_calculate_mode', _TAX_CALCULATE_AT_END) == _TAX_CALCULATE_INCREMENTAL) {
                     // tax calculated along the way.
                     // we have discounted the 'total amount taxable' so that means we need to reduce the tax amount by that much as well.
                     foreach ($invoice['taxes'] as $invoice_tax_id => $invoice_tax) {
                         $this_tax_discount = round($invoice['discount_amount'] * ($invoice['taxes'][$invoice_tax_id]['percent'] / 100), module_config::c('currency_decimal_places', 2));
                         $invoice['discount_amount_on_tax'] += $this_tax_discount;
                         if (!isset($invoice['taxes'][$invoice_tax_id]['total'])) {
                             $invoice['taxes'][$invoice_tax_id]['total'] = 0;
                         }
                         $invoice['taxes'][$invoice_tax_id]['total'] -= $invoice['discount_amount'];
                         $invoice['taxes'][$invoice_tax_id]['amount'] -= $this_tax_discount;
                         $invoice['taxes'][$invoice_tax_id]['discount'] = $this_tax_discount;
                     }
                 } else {
                     // we work out what the tax would have been if there was no applied discount
                     // this is used in job.php
                     $invoice['taxes_backup'] = $invoice['taxes'];
                     $invoice['total_sub_amount_taxable_backup'] = $invoice['total_sub_amount_taxable'];
                     $total_tax_before_discount = 0;
                     foreach ($invoice['taxes'] as $invoice_tax_id => $invoice_tax) {
                         $invoice['taxes'][$invoice_tax_id]['total'] = $invoice['total_sub_amount_taxable'];
                         $invoice['taxes'][$invoice_tax_id]['amount'] = round($invoice['total_sub_amount_taxable'] * ($invoice_tax['percent'] / 100), module_config::c('currency_decimal_places', 2));
                         // here we adjust the 'total_sub_amount_taxable' to include the value from the previous calculation.
                         // this is for multiple taxes that addup as they go (eg: Canada)
                         if (isset($invoice_tax['increment']) && $invoice_tax['increment']) {
                             $invoice['total_sub_amount_taxable'] += $invoice['taxes'][$invoice_tax_id]['amount'];
                         }
                         $total_tax_before_discount += $invoice['taxes'][$invoice_tax_id]['amount'];
                     }
                     $invoice['taxes'] = $invoice['taxes_backup'];
                     $invoice['total_sub_amount_taxable'] = $invoice['total_sub_amount_taxable_backup'];
                 }
                 // remove the discount amount from the 'sub total' and the 'taxable total' but don't go negative on it.
                 // remove the discount from any non-taxable portion first.
                 $non_taxable_amount = $invoice['total_sub_amount'] - $invoice['total_sub_amount_taxable'];
                 $non_taxable_discount = min($invoice['discount_amount'], $non_taxable_amount);
                 $taxable_discount = $invoice['discount_amount'] - $non_taxable_discount;
                 //echo "non tax $non_taxable_amount \n nontax discount: $non_taxable_discount \n tax discount: $taxable_discount \n";print_r($invoice);exit;
                 $invoice['total_sub_amount'] -= $invoice['discount_amount'];
                 $invoice['total_sub_amount_taxable'] -= $taxable_discount;
                 //                $invoice['total_sub_amount']-=$invoice['discount_amount'];
                 //                $invoice['total_sub_amount_taxable']-=$invoice['discount_amount'];
             }
         }
     }
     //$invoice['total_hours_remain'] = $invoice['total_hours'] - $invoice['total_hours_completed'];
     //$invoice['total_percent_complete'] = $invoice['total_hours'] > 0 ? round($invoice['total_hours_remain'] / $invoice['total_hours'],2) : 0;
     //if(isset($invoice['total_tax_rate'])){
     if (module_config::c('tax_calculate_mode', _TAX_CALCULATE_AT_END) == _TAX_CALCULATE_INCREMENTAL && isset($invoice['total_tax']) && $invoice['total_tax'] > 0) {
         // tax already calculated above.
     } else {
         if (module_config::c('tax_calculate_mode', _TAX_CALCULATE_AT_END) == _TAX_CALCULATE_AT_END) {
             // tax needs to be calculated based on the total_sub_amount_taxable
             $previous_invoice_tax_id = false;
             foreach ($invoice['taxes'] as $invoice_tax_id => $invoice_tax) {
                 $invoice['taxes'][$invoice_tax_id]['total'] = $invoice['total_sub_amount_taxable'];
                 if (isset($invoice_tax['increment']) && $invoice_tax['increment'] && $previous_invoice_tax_id) {
                     $invoice['taxes'][$invoice_tax_id]['total'] += $invoice['taxes'][$previous_invoice_tax_id]['amount'];
                 }
                 $invoice['taxes'][$invoice_tax_id]['amount'] = round($invoice['taxes'][$invoice_tax_id]['total'] * ($invoice_tax['percent'] / 100), module_config::c('currency_decimal_places', 2));
                 // here we adjust the 'total_sub_amount_taxable' to include the value from the previous calculation.
                 // this is for multiple taxes that addup as they go (eg: Canada)
                 $previous_invoice_tax_id = $invoice_tax_id;
             }
             //$invoice['total_tax'] = round(($invoice['total_sub_amount_taxable'] * ($invoice['total_tax_rate'] / 100)),module_config::c('currency_decimal_places',2));
         } else {
             //$invoice['total_tax'] = 0;
         }
     }
     if (isset($invoice['tax_type']) && $invoice['tax_type'] == 1) {
         // hack! not completely correct, oh well.
         // todo - make this work with more than 1 tax rate.
         // $amount / 1.05  ( this is 1 + tax %)
         // this will only work if a single tax has been included.
         if (is_array($invoice['taxes']) && count($invoice['taxes']) > 1) {
             set_error('Included tax calculation only works with 1 tax rate');
         } else {
             if (is_array($invoice['taxes']) && count($invoice['taxes'])) {
                 reset($invoice['taxes']);
                 $invoice_tax_id = key($invoice['taxes']);
                 if (isset($invoice['taxes'][$invoice_tax_id])) {
                     $taxable_amount = $invoice['total_sub_amount_taxable'] / (1 + $invoice['taxes'][$invoice_tax_id]['percent'] / 100);
                     $invoice['taxes'][$invoice_tax_id]['amount'] = $invoice['total_sub_amount_taxable'] - $taxable_amount;
                     $invoice['total_sub_amount'] = $invoice['total_sub_amount'] - $invoice['taxes'][$invoice_tax_id]['amount'];
                 }
             }
         }
     }
     $invoice['total_tax'] = 0;
     foreach ($invoice['taxes'] as $invoice_tax_id => $invoice_tax) {
         $invoice['total_tax'] += $invoice_tax['amount'];
     }
     if (isset($total_tax_before_discount)) {
         $invoice['discount_amount_on_tax'] += $total_tax_before_discount - $invoice['total_tax'];
     }
     $invoice['total_amount'] = $invoice['total_sub_amount'] + $invoice['total_tax'];
     if ($invoice['discount_type'] == _DISCOUNT_TYPE_AFTER_TAX) {
         $invoice['total_amount'] -= $invoice['discount_amount'];
     }
     $invoice['total_amount'] = round($invoice['total_amount'], module_config::c('currency_decimal_places', 2));
     $invoice['overdue'] = $invoice['date_due'] && $invoice['date_due'] != '0000-00-00' && (!$invoice['date_paid'] || $invoice['date_paid'] == '0000-00-00') && strtotime($invoice['date_due']) < strtotime(date('Y-m-d'));
     if ($basic === 1) {
         // so we don't go clearning cache and working out how much has been paid.
         // used in the finance module while displaying dashboard summary.
         return $invoice;
     }
     // find the user id if none exists.
     /*if($invoice['customer_id'] && !$invoice['user_id']){
           $customer_data = module_customer::get_customer($invoice['customer_id']);
           if($customer_data && $customer_data['customer_id'] == $invoice['customer_id']){
               if($customer_data['primary_user_id']){
                   $invoice['user_id'] = $customer_data['primary_user_id'];
               }else{
                   $customer_contacts = module_user::get_contacts(array('customer_id'=>$invoice['customer_id']));
                   foreach($customer_contacts as $contact){
                       // todo - search roles or something to find the accountant.
                       $invoice['user_id'] = $contact['user_id'];
                       break;
                   }
               }
           }
       }*/
     $paid = 0;
     /* START DEPOSITS */
     $invoice['total_amount_deposits'] = 0;
     // calculate deposits separately.
     $invoice['total_amount_deposits_tax'] = 0;
     // calculate deposits separately.
     //module_cache::clear_cache(); // no longer clearnig cache, it does it in get_invoice_payments.
     //module_cache::clear('invoice');
     foreach (self::get_invoice_payments($invoice_id) as $payment) {
         if ($payment['date_paid'] && $payment['date_paid'] != '0000-00-00') {
             if ($payment['payment_type'] == _INVOICE_PAYMENT_TYPE_DEPOSIT) {
                 // what invoice did this payment come from?
                 $deposit_invoice = module_invoice::get_invoice($payment['other_id']);
                 if ($deposit_invoice && $deposit_invoice['invoice_id'] == $payment['other_id']) {
                     $invoice['total_amount_deposits'] += min($deposit_invoice['total_amount'] - $deposit_invoice['total_tax'], $payment['amount'] - $deposit_invoice['total_tax']);
                     $invoice['total_amount_deposits_tax'] += $deposit_invoice['total_tax'];
                 }
             } else {
                 $paid += $payment['amount'];
             }
         }
     }
     if ($invoice['total_amount_deposits'] > 0) {
         // we need to reduce the 'total_amount' of this invoice so it doesn't double up with the other paid deposit invoice
         $invoice['total_amount'] -= $invoice['total_amount_deposits'];
     }
     if ($invoice['total_amount_deposits_tax'] > 0) {
         //$invoice['total_tax'] -= $invoice['total_amount_deposits_tax'];
         // we need to reduce the 'total_amount' of this invoice so it doesn't double up with the other paid deposit invoice
         $invoice['total_amount'] -= $invoice['total_amount_deposits_tax'];
     }
     /* END DEPOSITS */
     // any extra fees (eG: paypap fee?)
     $invoice['fees'] = self::get_fees($invoice_id, $invoice);
     foreach ($invoice['fees'] as $fee) {
         $invoice['total_amount'] += $fee['total'];
     }
     // dont go negative on payments:
     $invoice['total_amount_paid'] = max(0, min($invoice['total_amount'], $paid));
     $invoice['total_amount_credit'] = 0;
     if ($invoice['total_amount'] > 0 && $paid > $invoice['total_amount']) {
         // raise a credit against this customer for the difference.
         $invoice['total_amount_credit'] = round($paid - $invoice['total_amount'], 2);
         //echo $invoice['total_amount_overpaid'];exit;
     }
     if ($invoice['total_amount'] != $invoice['cached_total']) {
         if ((int) $invoice_id > 0) {
             update_insert('invoice_id', $invoice_id, 'invoice', array('cached_total' => $invoice['total_amount']));
         }
         $invoice['cached_total'] = $invoice['total_amount'];
     }
     $invoice['total_amount_due'] = round($invoice['total_amount'] - $invoice['total_amount_paid'], module_config::c('currency_decimal_places', 2));
     if ($invoice['date_cancel'] != '0000-00-00') {
         $invoice['total_amount_due'] = 0;
     }
     // a special addition for deposit invoices.
     if (isset($invoice['deposit_job_id']) && $invoice['deposit_job_id']) {
         // we find out how much deposit has actually been paid
         // and how much is remaining that hasn't been allocated to any other invoices
         $invoice['deposit_remaining'] = 0;
         if ($invoice['total_amount_paid'] > 0) {
             $invoice['deposit_remaining'] = $invoice['total_amount_paid'];
             $payments = get_multiple('invoice_payment', array('payment_type' => _INVOICE_PAYMENT_TYPE_DEPOSIT, 'other_id' => $invoice['invoice_id']));
             foreach ($payments as $payment) {
                 $invoice['deposit_remaining'] = $invoice['deposit_remaining'] - $payment['amount'];
             }
         }
     }
     // save our database cache values:
     if ((int) $invoice_id > 0) {
         foreach (array('total_amount', 'total_amount_due') as $cacheable_item) {
             if (isset($invoice[$cacheable_item]) && (!isset($original_invoice) || !isset($original_invoice['c_' . $cacheable_item]) || $original_invoice['c_' . $cacheable_item] != $invoice[$cacheable_item])) {
                 // cacheable items can be the same name or prefixed with c_
                 update_insert('invoice_id', $invoice_id, 'invoice', array("c_{$cacheable_item}" => $invoice[$cacheable_item]));
                 $invoice["c_{$cacheable_item}"] = $invoice[$cacheable_item];
             }
         }
     }
     if (isset($cache_key)) {
         module_cache::put('invoice', $cache_key, $invoice, $cache_timeout);
     }
     return $invoice;
 }
Пример #24
0
 public static function get_customer_restrictions()
 {
     if (!self::is_logged_in()) {
         return array(-1 => -1);
     }
     /*
     new feature: we use this function instead of our hardcoded:
     switch($customer_access){
         case _CUSTOMER_ACCESS_ALL:
         case _CUSTOMER_ACCESS_CONTACTS:
         case _CUSTOMER_ACCESS_TASKS:
         case _CUSTOMER_ACCESS_STAFF:
     }
     through out the system.
     */
     /*$res = (isset($_SESSION['_restrict_customer_id'])) ? $_SESSION['_restrict_customer_id'] : false;
       if(!is_array($res) && $res > 0){
           $res = array($res);
       }*/
     if (isset(self::$customer_restrictions[module_security::get_loggedin_id()])) {
         return self::$customer_restrictions[module_security::get_loggedin_id()];
     }
     self::$customer_restrictions[module_security::get_loggedin_id()] = array();
     $customers = module_customer::get_customers(array(), array('columns' => 'c.customer_id', 'as_resource' => false));
     if (count($customers) > 0) {
         foreach ($customers as $customer) {
             self::$customer_restrictions[module_security::get_loggedin_id()][$customer['customer_id']] = $customer['customer_id'];
         }
     } else {
         self::$customer_restrictions[module_security::get_loggedin_id()] = array(-1 => -1);
     }
     return self::$customer_restrictions[module_security::get_loggedin_id()];
 }
Пример #25
0
if (!$user_safe) {
    die('fail');
}
$user_id = (int) $_REQUEST['user_id'];
$user = module_user::get_user($user_id);
if (!$user) {
    $user_id = 'new';
}
if (!$user && $user_id > 0) {
    // bad url. hack attempt?
    // direct back to customer page
    if (isset($_REQUEST['customer_id']) && (int) $_REQUEST['customer_id']) {
        redirect_browser(module_customer::link_open($_REQUEST['customer_id']));
    }
}
if ($user_id == 1 && module_security::get_loggedin_id() != 1) {
    set_error('Sorry, only the Administrator can access this page.');
    redirect_browser(_UCM_HOST . _BASE_HREF);
}
// permission check.
if (!$user_id) {
    // check if can create.
    module_security::check_page(array('category' => 'Config', 'page_name' => 'Users', 'module' => 'user', 'feature' => 'Create'));
    // are we creating a new user?
    $user['roles'] = array(array('security_role_id' => module_config::c('user_default_role', 0)));
} else {
    // check if can view/edit.
    module_security::check_page(array('category' => 'Config', 'page_name' => 'Users', 'module' => 'user', 'feature' => 'Edit'));
}
// work out the user type and invluce that particular file
/*$user_type_id = (int)$user['user_type_id'];
Пример #26
0
 public static function get_companys_access_restrictions()
 {
     if (self::$get_companys_access_restrictions_cache !== false) {
         return self::$get_companys_access_restrictions_cache;
     }
     $where = 'WHERE 1';
     $sql = "SELECT c.company_id  ";
     $from = " FROM `" . _DB_PREFIX . "company` c ";
     $company_access = self::get_company_data_access();
     switch ($company_access) {
         case _COMPANY_ACCESS_ALL:
             break;
         case _COMPANY_ACCESS_ASSIGNED:
             // we only want companies that are directly linked with the currently logged in user contact (from the staff user account settings area)
             $sql .= ", cur.user_id AS user_assigned ";
             $from .= " LEFT JOIN `" . _DB_PREFIX . "company_user_rel` cur ON c.company_id = cur.company_id ";
             //$where .= " AND (cur.user_id = ".(int)module_security::get_loggedin_id().")";
             break;
         case _COMPANY_ACCESS_CONTACT:
             // only parent company of current user account contact
             $sql .= ", u.user_id AS user_id1, uv.user_id AS user_id2 ";
             $from .= " LEFT JOIN `" . _DB_PREFIX . "company_customer` cc ON c.company_id = cc.company_id ";
             $from .= " LEFT JOIN `" . _DB_PREFIX . "user` u ON cc.customer_id = u.customer_id ";
             $from .= " LEFT JOIN `" . _DB_PREFIX . "company_vendor` cv ON c.company_id = cv.company_id ";
             $from .= " LEFT JOIN `" . _DB_PREFIX . "user` uv ON cv.vendor_id = uv.vendor_id ";
             //$where .= " AND (u.user_id = ".(int)module_security::get_loggedin_id()." OR uv.user_id = ".(int)module_security::get_loggedin_id().")";
             break;
     }
     $sql .= $from;
     $sql .= $where;
     //$sql .= " GROUP BY c.company_id ";
     $res = qa($sql);
     self::$get_companys_access_restrictions_cache = array();
     switch ($company_access) {
         case _COMPANY_ACCESS_ALL:
             break;
         case _COMPANY_ACCESS_ASSIGNED:
             // we only want companies that are directly linked with the currently logged in user contact (from the staff user account settings area)
             //$where .= " AND (cur.user_id = ".(int)module_security::get_loggedin_id().")";
             foreach ($res as $r) {
                 if ((int) $r['user_assigned'] > 0 && $r['user_assigned'] == module_security::get_loggedin_id()) {
                     // this is an assigned user! add this company to the list.
                     self::$get_companys_access_restrictions_cache[$r['company_id']] = $r['company_id'];
                 }
             }
             break;
         case _COMPANY_ACCESS_CONTACT:
             foreach ($res as $r) {
                 if ((int) $r['user_id1'] > 0 && $r['user_id1'] == module_security::get_loggedin_id()) {
                     // this is an assigned user! add this company to the list.
                     self::$get_companys_access_restrictions_cache[$r['company_id']] = $r['company_id'];
                 } else {
                     if ((int) $r['user_id2'] > 0 && $r['user_id2'] == module_security::get_loggedin_id()) {
                         // this is an assigned user! add this company to the list.
                         self::$get_companys_access_restrictions_cache[$r['company_id']] = $r['company_id'];
                     }
                 }
             }
             break;
     }
     if (!count(self::$get_companys_access_restrictions_cache) && count($res)) {
         // we dont have access to any copmpanies, use the special -1 case so SQl works correctly.
         self::$get_companys_access_restrictions_cache[-1] = -1;
     }
     return self::$get_companys_access_restrictions_cache;
 }
Пример #27
0
 public static function get_finance_summary($week_start, $week_end, $multiplyer = 1, $row_limit = 7)
 {
     $cache_key = 'finance_sum_' . md5(module_security::get_loggedin_id() . '_' . serialize(func_get_args()));
     $cache_timeout = module_config::c('cache_objects', 60);
     if ($cached_item = module_cache::get('finance', $cache_key)) {
         return $cached_item;
     }
     $base_href = module_finance::link_generate(false, array('full' => false, 'page' => 'dashboard_popup', 'arguments' => array('display_mode' => 'ajax')), array('foo'));
     $base_href .= '&';
     /*$base_href .= (strpos($base_href,'?')!==false) ? '&' : '?';
       $base_href .= 'display_mode=ajax&';
       $base_href .= 'home_page_stats=true&';*/
     // init structure:
     if ($multiplyer > 1) {
         $row_limit++;
     }
     for ($x = 0; $x < $row_limit; $x++) {
         //$time = strtotime("+$x days",strtotime($week_start));
         $time = strtotime("+" . $x * $multiplyer . " days", strtotime($week_start));
         $data[date("Ymd", $time)] = array("day" => $time, "hours" => 0, "amount" => 0, "amount_invoiced" => 0, "amount_paid" => 0, "amount_spent" => 0);
         if (class_exists('module_envato', false)) {
             $data[date("Ymd", $time)]['envato_earnings'] = 0;
         }
     }
     $data['total'] = array('day' => _l('Totals:'), 'week' => _l('Totals:'), 'hours' => 0, 'amount' => 0, 'amount_invoiced' => 0, 'amount_paid' => 0, 'amount_spent' => 0);
     if (class_exists('module_envato', false)) {
         $data['total']['envato_earnings'] = 0;
     }
     if (class_exists('module_job', false)) {
         module_debug::log(array('title' => 'Finance Dashboard Job', 'data' => ''));
         // find all task LOGS completed within these dayes
         $sql = "SELECT t.task_id, tl.date_created, t.hours AS task_hours, t.amount, tl.hours AS hours_logged, p.job_id, p.hourly_rate, t.date_done ";
         //            $sql .= " FROM `"._DB_PREFIX."task_log` tl ";
         //            $sql .= " LEFT JOIN `"._DB_PREFIX."task` t ON tl.task_id = t.task_id ";
         $sql .= " FROM `" . _DB_PREFIX . "task` t";
         $sql .= " LEFT JOIN `" . _DB_PREFIX . "task_log` tl ON t.task_id = tl.task_id ";
         $sql .= " LEFT JOIN `" . _DB_PREFIX . "job` p ON t.job_id = p.job_id";
         $sql .= " WHERE ( (tl.date_created >= '{$week_start}' AND tl.date_created < '{$week_end}') OR (t.fully_completed = 1 AND t.date_done >= '{$week_start}' AND t.date_done < '{$week_end}') )";
         $sql .= " AND t.job_id IN ( ";
         $valid_job_ids = module_job::get_valid_job_ids();
         if (count($valid_job_ids)) {
             foreach ($valid_job_ids as $valid_job_id) {
                 $sql .= (int) $valid_job_id['job_id'] . ", ";
             }
             $sql = rtrim($sql, ', ');
         } else {
             $sql .= ' NULL ';
         }
         $sql .= " ) ";
         //            echo $sql;
         $tasks = query($sql);
         $logged_tasks = array();
         while ($r = mysql_fetch_assoc($tasks)) {
             if (!$r['date_created']) {
                 $r['date_created'] = $r['date_done'];
             }
             if ($multiplyer > 1) {
                 $week_day = date('w', strtotime($r['date_created'])) - 1;
                 $r['date_created'] = date('Y-m-d', strtotime('-' . $week_day . ' days', strtotime($r['date_created'])));
             }
             $key = date("Ymd", strtotime($r['date_created']));
             if (!isset($data[$key])) {
                 // for some reason we're getting results here that shouldn't be in the list
                 // for now we just skip these results until I figure out why (only had 1 guy report this error, maybe misconfig)
                 continue;
             }
             // copied from dashboard_popup_hours_logged.php
             // needed get_tasks call to do the _JOB_TASK_ACCESS_ASSIGNED_ONLY permission check
             $jobtasks = module_job::get_tasks($r['job_id']);
             $task = isset($jobtasks[$r['task_id']]) ? $jobtasks[$r['task_id']] : false;
             if (!$task) {
                 continue;
             }
             if (!isset($task['manual_task_type']) || $task['manual_task_type'] < 0) {
                 $task['manual_task_type'] = $task['default_task_type'];
             }
             if (isset($r['hours_logged']) && $r['hours_logged'] > 0) {
                 if ($r['hours_logged'] == $task['completed']) {
                     // this listing is the only logged hours for this task.
                     if ($task['fully_completed']) {
                         // task complete, we show the final amount and hours.
                         if ($task['amount'] > 0) {
                             if ($task['manual_task_type'] == _TASK_TYPE_QTY_AMOUNT) {
                                 $display_amount = $task['amount'] * $task['hours'];
                             } else {
                                 $display_amount = $task['amount'];
                             }
                         } else {
                             $display_amount = $r['task_hours'] * $r['hourly_rate'];
                         }
                     } else {
                         // task isn't fully completed yet, just use hourly rate for now.
                         $display_amount = $r['hours_logged'] * $r['hourly_rate'];
                     }
                 } else {
                     // this is part of a bigger log of hours for this single task.
                     $display_amount = $r['hours_logged'] * $r['hourly_rate'];
                 }
                 $hours_logged = $r['task_hours'] > 0 ? $r['hours_logged'] : 0;
             } else {
                 // there are no logged hours for this particular task, but it is set to completed.
                 // we just assume it is completed on this day.
                 if ($task['amount'] > 0) {
                     if ($task['manual_task_type'] == _TASK_TYPE_QTY_AMOUNT) {
                         $display_amount = $task['amount'] * $task['hours'];
                     } else {
                         $display_amount = $task['amount'];
                     }
                 } else {
                     $display_amount = $r['task_hours'] * $r['hourly_rate'];
                 }
                 $hours_logged = $task['hours'];
             }
             $data[$key]['amount'] += $display_amount;
             $data['total']['amount'] += $display_amount;
             $data[$key]['hours'] += $hours_logged;
             $data['total']['hours'] += $hours_logged;
             /*$hourly_rate = $r['hourly_rate'];
               if($hours_logged > 0 && $r['amount'] > 0 && $hourly_rate > 0){
                   // there is a custom amount assigned to thsi task.
                   // only calculate this amount if the full hours is complete.
                   $hourly_rate = $r['amount'] / $r['task_hours'];
               }
               if($hours_logged > 0 && $hourly_rate > 0){
                   $data[$key]['amount'] += ($hours_logged * $hourly_rate);
                   $data['total']['amount'] += ($hours_logged * $hourly_rate);
               }*/
         }
     }
     module_debug::log(array('title' => 'Finance Dashboard Invoices', 'data' => ''));
     // find invoices sent this week.
     $sql = "SELECT i.* ";
     $sql .= " FROM `" . _DB_PREFIX . "invoice` i ";
     $sql .= " LEFT JOIN `" . _DB_PREFIX . "invoice_item` ii ON i.invoice_id = ii.invoice_id ";
     if (class_exists('module_job', false)) {
         $sql .= " LEFT JOIN `" . _DB_PREFIX . "task` t ON ii.task_id = t.task_id ";
         $sql .= " LEFT JOIN `" . _DB_PREFIX . "job` p ON t.job_id = p.job_id ";
     }
     $sql .= " WHERE (i.date_create >= '{$week_start}' AND i.date_create <= '{$week_end}')";
     $sql .= " GROUP BY i.invoice_id";
     // todo - sql in here to limit what they can see.
     $invoices = query($sql);
     // group invoices into days of the week.
     while ($invoice_data = mysql_fetch_assoc($invoices)) {
         //$invoice_data = module_invoice::get_invoice($i['invoice_id']);
         if ($invoice_data) {
             if ($multiplyer > 1) {
                 $week_day = date('w', strtotime($invoice_data['date_create'])) - 1;
                 $invoice_data['date_create'] = date('Y-m-d', strtotime('-' . $week_day . ' days', strtotime($invoice_data['date_create'])));
             }
             $key = date("Ymd", strtotime($invoice_data['date_create']));
             if (!isset($data[$key])) {
                 // for some reason we're getting results here that shouldn't be in the list
                 // for now we just skip these results until I figure out why (only had 1 guy report this error, maybe misconfig)
                 continue;
             }
             if (isset($data[$key])) {
                 $data[$key]['amount_invoiced'] += $invoice_data['c_total_amount'];
                 $data['total']['amount_invoiced'] += $invoice_data['c_total_amount'];
             }
         }
     }
     module_debug::log(array('title' => 'Finance Dashboard Finances', 'data' => ''));
     // find all payments made this week.
     // we also have to search for entries in the new "finance" table and make sure we dont double up here.
     $finance_records = module_finance::get_finances(array('date_from' => $week_start, 'date_to' => $week_end));
     foreach ($finance_records as $finance_record) {
         if (isset($finance_record['payment_type']) && ($finance_record['payment_type'] == _INVOICE_PAYMENT_TYPE_OVERPAYMENT_CREDIT || $finance_record['payment_type'] == _INVOICE_PAYMENT_TYPE_CREDIT)) {
             // CODE COPIED FROM FINANCE_LIST.PHP
             // dont add these ones to the totals on the dashboard
             continue;
         }
         if ($finance_record['credit'] > 0) {
             if ($multiplyer > 1) {
                 $week_day = date('w', strtotime($finance_record['transaction_date'])) - 1;
                 $finance_record['transaction_date'] = date('Y-m-d', strtotime('-' . $week_day . ' days', strtotime($finance_record['transaction_date'])));
             }
             $key = date("Ymd", strtotime($finance_record['transaction_date']));
             if (isset($data[$key])) {
                 $data[$key]['amount_paid'] += $finance_record['amount'];
                 $data['total']['amount_paid'] += $finance_record['amount'];
             }
         }
         if ($finance_record['debit'] > 0) {
             if ($multiplyer > 1) {
                 $week_day = date('w', strtotime($finance_record['transaction_date'])) - 1;
                 $finance_record['transaction_date'] = date('Y-m-d', strtotime('-' . $week_day . ' days', strtotime($finance_record['transaction_date'])));
             }
             $key = date("Ymd", strtotime($finance_record['transaction_date']));
             if (isset($data[$key])) {
                 $data[$key]['amount_spent'] += $finance_record['amount'];
                 $data['total']['amount_spent'] += $finance_record['amount'];
             }
         }
     }
     module_debug::log(array('title' => 'Finance Dashboard DONE!', 'data' => ''));
     /*$sql = "SELECT p.* ";
       $sql .= " FROM `"._DB_PREFIX."invoice_payment` p ";
       $sql .= " WHERE (p.date_paid >= '$week_start' AND p.date_paid <= '$week_end')";
       // todo - sql in here to limit what they can see.
       $payments = query($sql);
       // group invoices into days of the week.
       while($payment = mysql_fetch_assoc($payments)){
           //$invoice_data = module_invoice::get_invoice($i['invoice_id']);
           if($multiplyer > 1){
               $week_day = date('w',strtotime($payment['date_paid'])) - 1;
               $payment['date_paid'] = date('Y-m-d',strtotime('-'.$week_day.' days',strtotime($payment['date_paid'])));
           }
           $key = date("Ymd",strtotime($payment['date_paid']));
           if(isset($data[$key])){
               $data[$key]['amount_paid'] += $payment['amount'];
               $data['total']['amount_paid'] += $payment['amount'];
           }
       }*/
     if (class_exists('module_envato', false)) {
         $envato_currency = "USD";
         $envato = new envato_api();
         $local_currency = $envato->read_setting("local_currency", "AUD");
         $currency_convert_multiplier = $envato->currency_convert($envato_currency, $local_currency);
         // find summary of earnings between these dates in the envato statement.
         $week_start_time = strtotime($week_start);
         $week_end_time = strtotime($week_end);
         $sql = "SELECT * FROM `" . _DB_PREFIX . "envato_statement` s WHERE `time` >= '{$week_start_time}' AND `time` <= {$week_end_time}";
         $sql .= " AND ( `type` = 'sale' OR `type` = 'referral_cut' )";
         foreach (qa($sql) as $sale) {
             $sale_time = $sale['time'];
             if ($multiplyer > 1) {
                 $week_day = date('w', $sale_time) - 1;
                 $sale_time = strtotime('-' . $week_day . ' days', $sale_time);
             }
             $key = date("Ymd", $sale_time);
             if (!isset($data[$key])) {
                 continue;
             }
             $data[$key]['envato_earnings'] += round($currency_convert_multiplier * $sale['earnt'], 2);
             $data['total']['envato_earnings'] += round($currency_convert_multiplier * $sale['earnt'], 2);
             /*if($sale['type']=='sale'){
                   $sales_count++;
               }
               $sales_amount+= $sale['earnt'];*/
         }
     }
     if ($multiplyer > 1) {
         // dont want totals on previous weeks listing
         unset($data['total']);
     }
     foreach ($data as $data_id => $row) {
         //$row['amount'] = dollar($row['amount']);
         $row['chart_amount'] = $row['amount'];
         $row['amount'] = currency((int) $row['amount']);
         $row['chart_amount_invoiced'] = $row['amount_invoiced'];
         $row['amount_invoiced'] = currency((int) $row['amount_invoiced']);
         $row['chart_amount_paid'] = $row['amount_paid'];
         $row['amount_paid'] = currency((int) $row['amount_paid']);
         $row['chart_amount_spent'] = $row['amount_spent'];
         $row['amount_spent'] = currency((int) $row['amount_spent']);
         if (class_exists('module_envato', false)) {
             $row['chart_envato_earnings'] = $row['envato_earnings'];
             $row['envato_earnings'] = currency((int) $row['envato_earnings']);
         }
         // combine together
         $row['chart_hours'] = $row['hours'];
         $row['hours'] = sprintf('%s (%s)', $row['hours'], $row['amount']);
         if (is_numeric($row['day'])) {
             $time = $row['day'];
             $date = date('Y-m-d', $time);
             $row['date'] = $date;
             if ($multiplyer > 1) {
                 $date .= '|' . date('Y-m-d', strtotime('+' . $multiplyer . ' days', $time));
             }
             //$row['hours'] = '<a href="'.$base_href.'w=hours&date='.$date.'" class="summary_popup">'. _l('%s hours',$row['hours']) . '</a>';
             $row['hours_link'] = '<a href="' . $base_href . 'w=hours&date=' . $date . '" class="summary_popup">' . $row['hours'] . '</a>';
             $row['amount_link'] = '<a href="' . $base_href . 'w=hours&date=' . $date . '" class="summary_popup">' . $row['amount'] . '</a>';
             $row['amount_invoiced_link'] = '<a href="' . $base_href . 'w=amount_invoiced&date=' . $date . '" class="summary_popup">' . $row['amount_invoiced'] . '</a>';
             $row['amount_paid_link'] = '<a href="' . $base_href . 'w=amount_paid&date=' . $date . '" class="summary_popup">' . $row['amount_paid'] . '</a>';
             $row['amount_spent_link'] = '<a href="' . $base_href . 'w=amount_spent&date=' . $date . '" class="summary_popup">' . $row['amount_spent'] . '</a>';
             $row['day'] = _l(date('D', $time)) . ' ' . date('j', $time) . _l(date('S', $time));
             $row['week'] = _l(date('M', $time)) . ' ' . date('j', $time) . _l(date('S', $time));
             // if it's today.
             if ($time == strtotime(date("Y-m-d"))) {
                 $row['highlight'] = true;
             }
         } else {
         }
         $data[$data_id] = $row;
     }
     module_cache::put('finance', $cache_key, $data, $cache_timeout);
     return $data;
 }
Пример #28
0
    public function process()
    {
        if ("save_facebook" == $_REQUEST['_process']) {
            $social_facebook_id = isset($_REQUEST['social_facebook_id']) ? (int) $_REQUEST['social_facebook_id'] : 0;
            $facebook = new ucm_facebook_account($social_facebook_id);
            if (isset($_POST['butt_del']) && module_social::can_i('delete', 'Facebook', 'Social', 'social')) {
                if (module_form::confirm_delete('social_facebook_id', "Really delete this Facebook account from the system? All messages will be lost.", self::link_open($_REQUEST['social_facebook_id']))) {
                    $facebook->delete();
                    set_message("Facebook account deleted successfully");
                    redirect_browser(self::link_open(false));
                }
            }
            $facebook->save_data($_POST);
            $social_facebook_id = $facebook->get('social_facebook_id');
            if (isset($_POST['butt_save_connect'])) {
                $redirect = $this->link_open($social_facebook_id, false, false, 'facebook_account_connect');
            } else {
                set_message('Facebook account saved successfully');
                $redirect = $this->link_open($social_facebook_id);
            }
            redirect_browser($redirect);
            exit;
        } else {
            if ("send_facebook_message" == $_REQUEST['_process']) {
                if (module_form::check_secure_key()) {
                    $social_facebook_id = isset($_REQUEST['social_facebook_id']) ? (int) $_REQUEST['social_facebook_id'] : 0;
                    $facebook = new ucm_facebook_account($social_facebook_id);
                    if ($social_facebook_id && $facebook->get('social_facebook_id') == $social_facebook_id) {
                        // queue the message into the facebook_message table
                        // if there's a scheduled date in the past we send it in the past, no date we send straight away, date in the future we leave it in the db table for the cron job to pick up.
                        //print_r($_POST);exit;
                        $send_time = false;
                        // default: now
                        if (isset($_POST['schedule_date']) && isset($_POST['schedule_time']) && !empty($_POST['schedule_date']) && !empty($_POST['schedule_time'])) {
                            $date = $_POST['schedule_date'];
                            $time_hack = $_POST['schedule_time'];
                            $time_hack = str_ireplace('am', '', $time_hack);
                            $time_hack = str_ireplace('pm', '', $time_hack);
                            $bits = explode(':', $time_hack);
                            if (strpos($_POST['schedule_time'], 'pm')) {
                                $bits[0] += 12;
                            }
                            // add the time if it exists
                            $date .= ' ' . implode(':', $bits) . ':00';
                            $send_time = strtotime(input_date($date, true));
                        } else {
                            if (isset($_POST['schedule_date']) && !empty($_POST['schedule_date'])) {
                                $send_time = strtotime(input_date($_POST['schedule_date'], true));
                            }
                        }
                        //echo print_date($send_time,true);
                        //echo '<br>';
                        //echo date('c',$send_time);
                        //exit;
                        /* @var $available_pages ucm_facebook_page[] */
                        $available_pages = $facebook->get('pages');
                        $send_pages = isset($_POST['compose_page_id']) && is_array($_POST['compose_page_id']) ? $_POST['compose_page_id'] : array();
                        $page_count = 0;
                        if ($send_pages) {
                            foreach ($send_pages as $facebook_page_id => $tf) {
                                if (!$tf) {
                                    continue;
                                }
                                // see if this is an available page.
                                if (isset($available_pages[$facebook_page_id])) {
                                    // push to db! then send.
                                    $facebook_message = new ucm_facebook_message($facebook, $available_pages[$facebook_page_id], false);
                                    $facebook_message->create_new();
                                    $facebook_message->update('social_facebook_page_id', $available_pages[$facebook_page_id]->get('social_facebook_page_id'));
                                    $facebook_message->update('social_facebook_id', $facebook->get('social_facebook_id'));
                                    $facebook_message->update('summary', isset($_POST['message']) ? $_POST['message'] : '');
                                    $facebook_message->update('type', 'pending');
                                    $facebook_message->update('link', isset($_POST['link']) ? $_POST['link'] : '');
                                    $facebook_message->update('data', json_encode($_POST));
                                    $facebook_message->update('user_id', module_security::get_loggedin_id());
                                    // do we send this one now? or schedule it later.
                                    $facebook_message->update('status', _SOCIAL_MESSAGE_STATUS_PENDINGSEND);
                                    if ($send_time) {
                                        // schedule for sending at a different time (now or in the past)
                                        $facebook_message->update('last_active', $send_time);
                                    } else {
                                        // send it now.
                                        $facebook_message->update('last_active', 0);
                                    }
                                    if (isset($_FILES['picture']['tmp_name']) && is_uploaded_file($_FILES['picture']['tmp_name'])) {
                                        $facebook_message->add_attachment($_FILES['picture']['tmp_name']);
                                    }
                                    $facebook_message->send_queued(isset($_POST['debug']));
                                    $page_count++;
                                } else {
                                    // log error?
                                }
                            }
                        }
                        set_message(_l('Message delivered successfully to %s Facebook pages', $page_count));
                        $redirect = $this->link_open_message_view($social_facebook_id);
                        redirect_browser($redirect);
                    }
                }
            } else {
                if ("ajax_facebook_url_info" == $_REQUEST['_process']) {
                    header('Content-type: text/javascript');
                    $url = isset($_REQUEST['url']) ? $_REQUEST['url'] : false;
                    if (strlen($url) > 4 && preg_match('#https?://#', $url)) {
                        // pass this into graph api debugger to get some information back about the URL
                        $facebook = new ucm_facebook();
                        $data = $facebook->get_url_info($url);
                        // return the data formatted in json ready to be added into the relevant input boxes.
                        $data['link_picture'] = isset($data['image'][0]['url']) ? $data['image'][0]['url'] : '';
                        $data['link_name'] = isset($data['title']) ? $data['title'] : '';
                        $data['link_caption'] = isset($data['caption']) ? $data['caption'] : '';
                        $data['link_description'] = isset($data['description']) ? $data['description'] : '';
                        echo json_encode($data);
                    }
                    exit;
                } else {
                    if ("ajax_social_facebook" == $_REQUEST['_process']) {
                        // ajax functions from wdsocial. copied from the datafeed.php sample files.
                        header('Content-type: text/javascript');
                        if (module_form::check_secure_key()) {
                            // todo: check user has access to this message.
                            $social_facebook_id = isset($_REQUEST['social_facebook_id']) ? (int) $_REQUEST['social_facebook_id'] : 0;
                            //$facebook = new ucm_facebook_account($social_facebook_id);
                            //if($social_facebook_id && $facebook->get('social_facebook_id') == $social_facebook_id){
                            $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : false;
                            $message_id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
                            $facebook_message = new ucm_facebook_message();
                            $facebook_message->load($message_id);
                            //if($facebook_message->get('social_facebook_id') == $social_facebook_id){
                            switch ($action) {
                                case "send-message-reply":
                                    if (module_social::can_i('create', 'Facebook Comments', 'Social', 'social')) {
                                        $return = array();
                                        $message = isset($_POST['message']) && $_POST['message'] ? $_POST['message'] : '';
                                        $facebook_id = isset($_POST['facebook_id']) && $_POST['facebook_id'] ? $_POST['facebook_id'] : false;
                                        $debug = isset($_POST['debug']) && $_POST['debug'] ? $_POST['debug'] : false;
                                        if ($message) {
                                            if ($debug) {
                                                ob_start();
                                            }
                                            $facebook_message->send_reply($facebook_id, $message, $debug);
                                            if ($debug) {
                                                $return['message'] = ob_get_clean();
                                            } else {
                                                // todo - option to ask the user if they want to archive a message during the send.
                                                set_message(_l('Message sent and conversation archived.'));
                                                if ($social_facebook_id) {
                                                    $return['redirect'] = module_social_facebook::link_open_message_view($social_facebook_id);
                                                } else {
                                                    // return to the 'combined' view:
                                                }
                                            }
                                        }
                                        echo json_encode($return);
                                    }
                                    break;
                                case "set-answered":
                                    if (module_social::can_i('edit', 'Facebook Comments', 'Social', 'social')) {
                                        $facebook_message->update('status', _SOCIAL_MESSAGE_STATUS_ANSWERED);
                                        ?>

									$('.facebook_message_row[data-id=<?php 
                                        echo $message_id;
                                        ?>
]').hide();
									<?php 
                                    }
                                    break;
                                case "set-unanswered":
                                    if (module_social::can_i('edit', 'Facebook Comments', 'Social', 'social')) {
                                        $facebook_message->update('status', _SOCIAL_MESSAGE_STATUS_UNANSWERED);
                                        ?>

					                $('.facebook_message_row[data-id=<?php 
                                        echo $message_id;
                                        ?>
]').hide();
					                <?php 
                                    }
                                    break;
                            }
                            //echo 'The status is '.$facebook_message->get('status');
                            //}
                        }
                        // }
                        exit;
                    }
                }
            }
        }
    }
Пример #29
0
 function handle_hook($hook, $calling_module = false, $owner_table = false, $key_name = false, $key_value = false, $rel_data = false)
 {
     switch ($hook) {
         case "home_alerts":
             $alerts = array();
             if (module_config::c('allow_note_reminders', 1)) {
                 // find any jobs that are past the due date and dont have a finished date.
                 $key = _l('Note Reminder');
                 if (class_exists('module_dashboard', false)) {
                     module_dashboard::register_group($key, array('columns' => array('name' => _l('Reminder'), 'type' => _l('Type'), 'full_link' => _l('Link'), 'date' => _l('Date'), 'days' => _l('Date'))));
                 }
                 $sql = "SELECT * FROM `" . _DB_PREFIX . "note` n ";
                 $sql .= " WHERE n.`reminder` = 1 AND n.note_time < " . (int) strtotime('+' . module_config::c('alert_days_in_future', 5) . ' days') . "";
                 $sql .= " AND ( n.`user_id` = 0 OR n.`user_id` = " . module_security::get_loggedin_id() . ")";
                 $sql .= " ORDER BY n.note_time ASC";
                 $tasks = qa($sql);
                 foreach ($tasks as $task) {
                     $alert_res = process_alert(date('Y-m-d', $task['note_time']), $key);
                     if ($alert_res) {
                         $alert_res['link'] = $task['rel_data'];
                         // fix for linking when changing folder.
                         $alert_res['type'] = _l(ucwords($task['owner_table']));
                         switch ($task['owner_table']) {
                             case 'user':
                                 $user = module_user::get_user($task['owner_id']);
                                 if ($user['customer_id'] || $user['vendor_id']) {
                                     $alert_res['link'] = module_user::link_open_contact($task['owner_id'], false, $user);
                                     $alert_res['full_link'] = module_user::link_open_contact($task['owner_id'], true, $user);
                                     $alert_res['type'] = _l('Contact');
                                 } else {
                                     $alert_res['link'] = module_user::link_open($task['owner_id'], false, $user);
                                     $alert_res['full_link'] = module_user::link_open($task['owner_id'], true, $user);
                                 }
                                 break;
                             case 'invoice':
                                 $invoice_data = module_invoice::get_invoice($task['owner_id'], true);
                                 if (!$invoice_data || !isset($invoice_data['invoice_id']) || $invoice_data['invoice_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_invoice::link_open($task['owner_id'], false, $invoice_data);
                                 $alert_res['full_link'] = module_invoice::link_open($task['owner_id'], true, $invoice_data);
                                 break;
                             case 'quote':
                                 $quote_data = module_quote::get_quote($task['owner_id'], true);
                                 if (!$quote_data || !isset($quote_data['quote_id']) || $quote_data['quote_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_quote::link_open($task['owner_id'], false, $quote_data);
                                 $alert_res['full_link'] = module_quote::link_open($task['owner_id'], true, $quote_data);
                                 break;
                             case 'website':
                                 $website_data = module_website::get_website($task['owner_id']);
                                 if (!$website_data || !isset($website_data['website_id']) || $website_data['website_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_website::link_open($task['owner_id'], false);
                                 $alert_res['full_link'] = module_website::link_open($task['owner_id'], true);
                                 break;
                             case 'customer':
                                 $customer_data = module_customer::get_customer($task['owner_id']);
                                 if (!$customer_data || !isset($customer_data['customer_id']) || $customer_data['customer_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_customer::link_open($task['owner_id'], false, $customer_data);
                                 $alert_res['full_link'] = module_customer::link_open($task['owner_id'], true, $customer_data);
                                 break;
                             case 'vendor':
                                 $vendor_data = module_vendor::get_vendor($task['owner_id']);
                                 if (!$vendor_data || !isset($vendor_data['vendor_id']) || $vendor_data['vendor_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_vendor::link_open($task['owner_id'], false, $vendor_data);
                                 $alert_res['full_link'] = module_vendor::link_open($task['owner_id'], true, $vendor_data);
                                 break;
                             case 'job':
                                 $job_data = module_job::get_job($task['owner_id']);
                                 if (!$job_data || !isset($job_data['job_id']) || $job_data['job_id'] != $task['owner_id']) {
                                     continue 2;
                                 }
                                 $alert_res['link'] = module_job::link_open($task['owner_id'], false, $job_data);
                                 $alert_res['full_link'] = module_job::link_open($task['owner_id'], true, $job_data);
                                 break;
                                 // todo - add others.
                         }
                         $alert_res['name'] = $task['note'];
                         $alert_res['date'] = print_date($alert_res['date']);
                         $alert_res['time'] = $task['note_time'];
                         $alerts[] = $alert_res;
                     }
                 }
             }
             return $alerts;
             break;
             /*case "note_list":
             				if($owner_id && $owner_id != 'new'){
             
             					$note_items = $this->get_notes(array("owner_table"=>$owner_table,"owner_id"=>$owner_id));
             					foreach($note_items as &$note_item){
             						// do it in loop here because of $this issues in static method below.
             						// instead of include file below.
             						$note_item['html'] = $this->print_note($note_item['note_id']);
             					}
             					include("pages/note_list.php");
             				}else{
             					echo 'Please save first before creating notes.';
             				}
             				break;*/
         /*case "note_list":
         				if($owner_id && $owner_id != 'new'){
         
         					$note_items = $this->get_notes(array("owner_table"=>$owner_table,"owner_id"=>$owner_id));
         					foreach($note_items as &$note_item){
         						// do it in loop here because of $this issues in static method below.
         						// instead of include file below.
         						$note_item['html'] = $this->print_note($note_item['note_id']);
         					}
         					include("pages/note_list.php");
         				}else{
         					echo 'Please save first before creating notes.';
         				}
         				break;*/
         case "note_delete":
             // find the key we are saving this address against.
             $owner_id = (int) $key_value;
             if (!$owner_id || $owner_id == 'new') {
                 // find one in the post data.
                 if (isset($_REQUEST[$key_name])) {
                     $owner_id = $_REQUEST[$key_name];
                 }
             }
             $note_hash = md5($owner_id . '|' . $owner_table);
             // just for posting unique arrays.
             if ($owner_table && $owner_id) {
                 $this->note_delete($owner_table, $owner_id);
             }
             break;
     }
 }
Пример #30
0
 public function replace_content()
 {
     $content = $this->content;
     $this->add_tags($this->template_key, $this->values);
     // add todays date values
     if (!isset($this->values['day'])) {
         $this->values['day'] = date('d');
     }
     if (!isset($this->values['month'])) {
         $this->values['month'] = date('m');
     }
     if (!isset($this->values['year'])) {
         $this->values['year'] = date('y');
     }
     if (!isset($this->values['current_user']) && module_security::is_logged_in()) {
         $this->values['current_user'] = module_security::get_loggedin_id();
         $user_details = module_user::get_replace_fields(module_security::get_loggedin_id());
         foreach ($user_details as $key => $val) {
             $this->values['current_' . $key . ''] = $val;
         }
     }
     // basic conditional tags - eg: {if:name}Dear {name},{else:name}Hello,{endif:name}
     // todo - support nested if - pass to template module.
     $debug = false;
     if (preg_match_all('#\\{if:([^\\}=]+)([^\\}]*)\\}(.*){endif:\\1\\}.*#imsU', $content, $matches)) {
         foreach ($matches[1] as $key => $template_tag) {
             // does this first if have a conditional statement (eg: {if:STATUS=New}sdfasdf{else}asdfasdf{/if:STATUS}
             $bits = preg_split('#{else[^\\}]*}#', $matches[3][$key]);
             preg_match_all('#\\{(else)?(if:([^\\}=]+)([^\\}]*))?\\}#ims', $matches[0][$key], $elseif_matches);
             $new_content = false;
             if ($debug) {
                 echo $matches[0][$key] . "\n";
             }
             if ($debug) {
                 print_r($bits);
             }
             if ($debug) {
                 print_r($elseif_matches);
             }
             foreach ($elseif_matches[0] as $elseif_key => $elseif_condition) {
                 $template_tag_value = isset($this->values[strtolower($elseif_matches[3][$elseif_key])]) ? trim($this->values[strtolower($elseif_matches[3][$elseif_key])]) : '';
                 if (!strlen(trim($elseif_matches[3][$elseif_key]))) {
                     // we are at the final {else} statement, this means all other checks before have failed. we use this content.
                     if ($debug) {
                         echo "Reached final {else} statement, using this value\n";
                     }
                     $new_content = $bits[$elseif_key];
                     break;
                 } else {
                     if ($debug) {
                         echo "Checking {$elseif_condition} against " . $elseif_matches[3][$elseif_key] . " which has the value: " . $template_tag_value . "\n";
                     }
                     if (strlen($elseif_matches[4][$elseif_key]) && $elseif_matches[4][$elseif_key][0] == '=') {
                         // the if/elseif tag is checking a condition, rather than just an "does exist" check
                         $check_matching_value = ltrim(trim($elseif_matches[4][$elseif_key]), '=');
                         if ($debug) {
                             echo "Checking if it matches {$check_matching_value} \n";
                         }
                         if ($check_matching_value == $template_tag_value) {
                             if ($debug) {
                                 echo "YES WE HAVE A MATCH \n";
                             }
                             // this first if statement matches this query! yes!
                             // use its value in the final $new_content
                             $new_content = $bits[$elseif_key];
                             break;
                         } else {
                             if ($debug) {
                                 echo "No match this time \n";
                             }
                         }
                     } else {
                         // we're just checking if this value exists or not.
                         if (strlen($template_tag_value) > 0 && $template_tag_value != '0000-00-00' && $template_tag_value != _l('N/A')) {
                             // it's a match!
                             $new_content = $bits[$elseif_key];
                             break;
                         } else {
                             // no match, move onto next bit.
                         }
                     }
                 }
             }
             if ($debug) {
                 echo "Final content to use will be: \n" . $new_content;
             }
             $content = str_replace($matches[0][$key], $new_content, $content);
         }
     }
     foreach ($this->values as $key => $val) {
         if (is_array($val)) {
             continue;
         }
         // if this isn't a html field we add newlines.
         if (!preg_match('#<[^>]+>#', $val)) {
             // raw text. nl2br
             $val = nl2br($val);
         }
         $content = str_replace('{' . strtoupper($key) . '}', $val, $content);
         // we perform some basic arithmetic on some replace fields.
         if (preg_match_all('#\\{(currency:)?' . preg_quote(strtoupper($key), '#') . '([*+-])([\\d\\.]+)\\}#', $content, $matches)) {
             // pull the "number" portion out of this string for math processing.
             // string could look like this: "$150.10 USD"
             $mathval = $originalval = $val;
             if (preg_match('#([\\d.,]+)#', $val, $mathvalmatches)) {
                 $mathval = $originalval = $mathvalmatches[1];
             }
             foreach ($matches[0] as $i => $v) {
                 $mathval = $originalval;
                 if ($matches[2][$i] == '-') {
                     $mathval = $mathval - $matches[3][$i];
                 } else {
                     if ($matches[2][$i] == '+') {
                         $mathval = $mathval + $matches[3][$i];
                     } else {
                         if ($matches[2][$i] == '*') {
                             $mathval = $mathval * $matches[3][$i];
                         }
                     }
                 }
                 if (strtolower($matches[1][$i]) == 'currency:') {
                     $mathval = dollar($mathval, true, isset($this->values['currency_id']) ? $this->values['currency_id'] : false);
                 }
                 $newval = str_replace($originalval, $mathval, $val);
                 $content = str_replace($v, $newval, $content);
             }
         }
         if (preg_match_all('#\\{currency:(' . preg_quote(strtoupper($key), '#') . ')\\}#', $content, $matches)) {
             foreach ($matches[0] as $i => $v) {
                 $content = str_replace($v, dollar($val, true, isset($this->values['currency_id']) ? $this->values['currency_id'] : false), $content);
             }
         }
         // we perform some arithmetic on date fields.
         $matches = false;
         if (stripos($key, 'date') !== false && $val && strlen($val) > 6 && preg_match_all('#' . preg_quote('{' . strtoupper($key), '#') . '((?>[+-]\\d+[ymd])*)\\}#', $content, $matches)) {
             //$processed_date = (input_date($val)); $processed_date_timeo =
             $processed_date_time = strtotime(input_date($val));
             foreach ($matches[0] as $i => $v) {
                 if (preg_match_all('#([+-])(\\d+)([ymd])#', $matches[1][$i], $date_math)) {
                     foreach ($date_math[1] as $di => $dv) {
                         $period = $date_math[3][$di];
                         $period = $period == 'd' ? 'day' : ($period == 'm' ? 'month' : ($period == 'y' ? 'year' : 'days'));
                         //echo $dv.$date_math[2][$di]." ".$period."\n";
                         $processed_date_time = strtotime($dv . $date_math[2][$di] . " " . $period, $processed_date_time);
                     }
                     $content = str_replace($v, print_date($processed_date_time), $content);
                     //echo "Processing date: $val - $processed_date (time: $processed_date_timeo / ".print_date($processed_date_timeo).") with result of: ".print_date($processed_date_time); exit;
                 }
             }
         }
         // we perform some date splitting
         $matches = false;
         if (stripos($key, 'date') !== false && $val && strlen($val) > 6 && preg_match_all('#' . preg_quote('{' . strtoupper($key), '#') . '-([ymdYMDjlSWFn])\\}#', $content, $matches)) {
             $processed_date_time = strtotime(input_date($val));
             foreach ($matches[0] as $i => $v) {
                 $content = str_replace($v, date($matches[1][$i], $processed_date_time), $content);
             }
         }
         //$val = str_replace(array('\\', '$'), array('\\\\', '\$'), $val);
         //$content = preg_replace('/\{'.strtoupper(preg_quote($key,'/')).'\}/',$val,$content);
     }
     if (preg_match_all('#\\{l:([^\\}]+)\\}#', $content, $matches)) {
         foreach ($matches[1] as $key => $label) {
             $content = str_replace($matches[0][$key], _l($label), $content);
         }
     }
     return $content;
 }