Ejemplo n.º 1
0
    public function pre_menu()
    {
        if ($this->can_i('view', 'Members')) {
            // how many members are there?
            $link_name = _l('Members');
            if (module_config::c('member_show_summary', 1)) {
                $member_count = module_cache::get('member', 'member_menu_count');
                if ($member_count === false) {
                    $sql = "SELECT COUNT(member_id) AS c FROM `" . _DB_PREFIX . "member` m";
                    $res = qa1($sql);
                    $member_count = $res['c'];
                    module_cache::put('member', 'member_menu_count', $member_count);
                }
                if ($member_count > 0) {
                    $link_name .= " <span class='menu_label'>" . $member_count . "</span> ";
                }
            }
            $this->links['members'] = array("name" => $link_name, "p" => "member_admin", "args" => array('member_id' => false));
            if (class_exists('module_newsletter', false) && module_config::c('member_menu_under_newsletter', 1)) {
                $this->links['members']['holder_module'] = 'newsletter';
                $this->links['members']['holder_module_page'] = 'newsletter_admin';
                $this->links['members']['menu_include_parent'] = 0;
                $this->links['members']['allow_nesting'] = 1;
            }
        }
        if (class_exists('module_template', false)) {
            module_template::init_template('member_subscription_form', '<h2>Subscribe</h2>
<form action="" method="post">
    <p>Please Enter Your Email Address: <input type="text" name="member[email]" value="{EMAIL}"> </p>
    <p>Please Enter Your First Name: <input type="text" name="member[first_name]" value="{FIRST_NAME}"> </p>
    <p>Please Enter Your Last Name: <input type="text" name="member[last_name]" value="{LAST_NAME}"> </p>
    <p>Please Enter Your Business Name: <input type="text" name="member[business]" value="{BUSINESS}"> </p>
    <p>Please Enter Your Phone Number: <input type="text" name="member[phone]" value="{PHONE}"> </p>
    <p>
    Please choose your newsletter subscription options: <br/>
    {NEWSLETTER_OPTIONS}
    </p>
    <p><input type="submit" name="confirm" value="Subscribe"></p>
</form>
    ', 'Used when a user wishes to subscribe.', 'code', array());
            module_template::init_template('member_subscription_error', '<h2>Subscription Error</h2>
    <p>Sorry there was an error when processing your request:</p>
    <p>{MESSAGE}</p>
    ', 'Displayed when subscription fails (eg: missing email address).', 'code', array('MESSAGE' => 'Message to the user'));
            module_template::init_template('member_subscription_success', '<h2>Subscription Success</h2>
    <p>Thank you, subscription successful.</p>
    <p>A message has been sent to your email address ({EMAIL}) to confirm your newsletter subscription.</p>
    ', 'Displayed when subscription is successful.', 'code', array('EMAIL' => 'Users email address'));
            module_template::init_template('member_update_details_success', '<h2>Subscription Success</h2>
    <p>Thank you, subscription details updated.</p>
    <p>Your email address: ({EMAIL})</p>
    ', 'Displayed when updating details is successful.', 'code', array('EMAIL' => 'Users email address'));
        }
    }
Ejemplo n.º 2
0
 public function is_allowed_for_invoice($invoice_id)
 {
     if (!self::is_enabled()) {
         return false;
     }
     $old_default = module_config::c('__inv_google_' . $invoice_id);
     if ($old_default !== false) {
         $this->set_allowed_for_invoice($invoice_id, $old_default);
         delete_from_db('config', 'key', '__inv_google_' . $invoice_id);
         module_cache::clear('config');
         return $old_default;
     }
     // check for manually enabled invoice payment method.
     $invoice_payment_methods = module_invoice::get_invoice_payment_methods($invoice_id);
     if (isset($invoice_payment_methods['google'])) {
         return $invoice_payment_methods['google']['enabled'];
     }
     return module_config::c('payment_method_google_enabled_default', 1);
 }
Ejemplo n.º 3
0
 public function is_allowed_for_invoice($invoice_id)
 {
     if (!self::is_enabled()) {
         return false;
     }
     $old_default = module_config::c('__inv_coinbase_' . $invoice_id);
     if ($old_default !== false) {
         $this->set_allowed_for_invoice($invoice_id, $old_default);
         delete_from_db('config', 'key', '__inv_coinbase_' . $invoice_id);
         module_cache::clear('config');
         return $old_default;
     }
     // check for manually enabled invoice payment method.
     $invoice_payment_methods = module_invoice::get_invoice_payment_methods($invoice_id);
     if (isset($invoice_payment_methods['coinbase'])) {
         return $invoice_payment_methods['coinbase']['enabled'];
     }
     // check currency and value amounts
     $invoice_data = module_invoice::get_invoice($invoice_id);
     $cur = trim(strtolower(module_config::c('payment_method_coinbase_currency', '')));
     $dollar_limit = module_config::c('payment_method_coinbase_limit_type', 'above');
     $dollar_value = module_config::c('payment_method_coinbase_limit_value', 0);
     if ($dollar_limit == 'above' && $invoice_data['total_amount_due'] < $dollar_value) {
         return false;
     } else {
         if ($dollar_limit == 'below' && $invoice_data['total_amount_due'] > $dollar_value) {
             return false;
         }
     }
     if (strlen($cur) > 1) {
         $allowed_currencies = explode(',', $cur);
         if (count($allowed_currencies)) {
             $currency = module_config::get_currency($invoice_data['currency_id']);
             if (!in_array(strtolower($currency['code']), $allowed_currencies)) {
                 return false;
             }
         }
     }
     return module_config::c('payment_method_coinbase_enabled_default', 1);
 }
Ejemplo n.º 4
0
 public static function get_defaults($owner_table = false)
 {
     $defaults = array();
     $nextorder = array();
     if ($owner_table && strlen($owner_table)) {
         $where = " WHERE e.owner_table = '" . mysql_real_escape_string($owner_table) . "' ";
         $defaults[$owner_table] = array();
         $nextorder[$owner_table] = 0;
     } else {
         $where = '';
     }
     $sql = "SELECT `extra_default_id`,`extra_key`, `order`, `display_type`, `owner_table`, `searchable`, `field_type`, `options` FROM `" . _DB_PREFIX . "extra_default` e {$where} ORDER BY e.`order` ASC";
     foreach (qa($sql) as $r) {
         if (!isset($defaults[$r['owner_table']])) {
             $defaults[$r['owner_table']] = array();
         }
         if (!isset($nextorder[$r['owner_table']])) {
             $nextorder[$r['owner_table']] = 0;
         }
         $defaults[$r['owner_table']][$r['extra_key']] = array('key' => $r['extra_key'], 'order' => $r['order'], 'extra_default_id' => $r['extra_default_id'], 'display_type' => $r['display_type'], 'searchable' => $r['searchable'], 'field_type' => $r['field_type'], 'options' => isset($r['options']) ? @json_decode($r['options'], true) : array());
         $nextorder[$r['owner_table']] = max($r['order'], $nextorder[$r['owner_table']]);
     }
     // search database for keys.
     $sql = "SELECT `extra_key`,`owner_table` FROM `" . _DB_PREFIX . "extra` e {$where} GROUP BY e.extra_key";
     foreach (qa($sql) as $r) {
         if (!isset($nextorder[$r['owner_table']])) {
             $nextorder[$r['owner_table']] = 0;
         }
         if (!isset($defaults[$r['owner_table']]) || !isset($defaults[$r['owner_table']][$r['extra_key']])) {
             $nextorder[$r['owner_table']]++;
             $extra_default_id = update_insert('extra_default_id', false, 'extra_default', array('owner_table' => $r['owner_table'], 'extra_key' => $r['extra_key'], 'order' => $nextorder[$r['owner_table']], 'display_type' => 0));
             $defaults[$r['owner_table']][$r['extra_key']] = array();
             $defaults[$r['owner_table']][$r['extra_key']]['key'] = $r['extra_key'];
             $defaults[$r['owner_table']][$r['extra_key']]['order'] = $nextorder[$r['owner_table']];
             $defaults[$r['owner_table']][$r['extra_key']]['extra_default_id'] = $extra_default_id;
             $defaults[$r['owner_table']][$r['extra_key']]['display_type'] = 0;
             $defaults[$r['owner_table']][$r['extra_key']]['field_type'] = '';
             $defaults[$r['owner_table']][$r['extra_key']]['options'] = array();
             module_cache::clear_cache(false);
         }
         if (!isset($defaults[$r['owner_table']][$r['extra_key']]['order'])) {
             $defaults[$r['owner_table']][$r['extra_key']]['order'] = 0;
         }
         /*$defaults[$r['owner_table']][$r['extra_key']] = array(
               'key' => $r['extra_key'],
               'order'=> isset($defaults[$r['extra_key']]) ? $defaults[$r['extra_key']]['order'] : 0,
           );*/
     }
     if ($owner_table) {
         uasort($defaults[$owner_table], 'sort_extra_defaults');
         return $defaults[$owner_table];
     } else {
         return $defaults;
         //return all for settings area
     }
     /*        switch($owner_table){
                 case 'website':
                     $defaults = array(
                         array('key' => 'FTP Username',),
                         array('key' => 'FTP Password',),
                         array('key' => 'FTP Provider',),
                         array('key' => 'Host Username',),
                         array('key' => 'Host Password',),
                         array('key' => 'Host Provider',),
                         array('key' => 'WordPress User',),
                         array('key' => 'WordPress Pass',),
                         array('key' => 'Analytics Account',),
                         array('key' => 'Webmaster Account',),
                     );
                     break;
             }*/
 }
Ejemplo n.º 5
0
 public static function get_fields($table, $ignore = array(), $hidden = array(), $from_cache = false)
 {
     if (is_array($table) || !trim($table)) {
         return array();
     }
     if (isset(self::$fieldscache[$table])) {
         return self::$fieldscache[$table];
     }
     $res = $db_cache = array();
     if ($from_cache) {
         $db_cache = module_cache::get('db', 'db_fields_' . $table);
         if (!is_array($db_cache)) {
             $db_cache = array();
         }
         if (isset($db_cache[$table])) {
             $res = $db_cache[$table];
         }
     }
     if (!count($res)) {
         $sql = "SHOW FIELDS FROM `" . _DB_PREFIX . "{$table}`";
         $res = qa($sql);
         if (!is_array($db_cache)) {
             $db_cache = array();
         }
         $db_cache[$table] = $res;
         module_cache::put('db', 'db_fields_' . $table, $db_cache, 172800);
     }
     $fields = array();
     foreach ($res as $r) {
         $format = "";
         $type = 'text';
         if (count($ignore) && in_array($r['Field'], $ignore)) {
             continue;
         }
         if (count($hidden) && in_array($r['Field'], $hidden)) {
             $type = "hidden";
             // new field for file.
         } else {
             if (preg_match("/^file_/", $r['Field']) && preg_match("/varchar\\((\\d+)\\)/", $r['Type'], $matches)) {
                 $type = "file";
                 $size = 50;
                 $maxlength = 255;
             } else {
                 if (preg_match("/varchar\\((\\d+)\\)/", $r['Type'], $matches)) {
                     $type = "text";
                     $size = max("10", min("30", $matches[1]));
                     $maxlength = $matches[1];
                 } else {
                     if (preg_match("/int/i", $r['Type']) || preg_match("/float/i", $r['Type'])) {
                         $format = array("/^\\d+\$/", "Integer");
                         $type = "number";
                         $maxlength = $size = 20;
                     } else {
                         if ($r['Type'] == "text") {
                             $type = "textarea";
                             $size = 0;
                         } else {
                             if ($r['Type'] == "date" || $r['Type'] == "datetime") {
                                 $format = array("/^\\d\\d\\d\\d-\\d\\d-\\d\\d\$/", "YYYY-MM-DD");
                                 $type = "date";
                                 $maxlength = $size = 20;
                             } else {
                                 if (preg_match("/decimal/", $r['Type']) || preg_match("/double/", $r['Type'])) {
                                     $format = array("/^\\d+\\.?[\\d+]?\$/", "Decimal");
                                     $type = "decimal";
                                     $maxlength = $size = 20;
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $required = false;
         if ($r['Null'] == "NO") {
             $required = true;
         }
         $fields[$r['Field']] = array("name" => $r['Field'], "type" => $type, "dbtype" => $r['Type'], "size" => $size, "maxlength" => $maxlength, "required" => $required, "format" => $format);
     }
     self::$fieldscache[$table] = $fields;
     return $fields;
 }
Ejemplo n.º 6
0
 private static function update_job_completion_status($job_id)
 {
     module_cache::clear('job');
     //module_cache::clear_cache();
     $data = self::save_job_cache($job_id);
     $return_status = $data['status'];
     $tasks = self::get_tasks($job_id);
     $all_completed = count($tasks) > 0;
     foreach ($tasks as $task) {
         if (module_config::c('job_task_log_all_hours', 1) && $task['fully_completed'] || !module_config::c('job_task_log_all_hours', 1) && ($task['fully_completed'] || $task['hours'] > 0 && $task['completed'] >= $task['hours'] || $task['hours'] <= 0 && $task['completed'] > 0)) {
             // this one is done!
         } else {
             $all_completed = false;
             break;
         }
     }
     if ($all_completed) {
         if (!isset($data['date_completed']) || !$data['date_completed'] || $data['date_completed'] == '0000-00-00') {
             // update, dont complete if no tasks.
             //if(count($tasks)){
             $return_status = $data['status'] == module_config::s('job_status_default', 'New') ? _l('Completed') : $data['status'];
             update_insert("job_id", $job_id, "job", array('date_completed' => date('Y-m-d'), 'status' => $return_status));
             //}
         }
     } else {
         // not completed. remove compelted date and reset the job status
         $return_status = $data['status'] == _l('Completed') ? module_config::s('job_status_default', 'New') : $data['status'];
         update_insert("job_id", $job_id, "job", array('date_completed' => '0000-00-00', 'status' => $return_status));
     }
     module_cache::clear('job');
     return $return_status;
 }
Ejemplo n.º 7
0
 private static function update_quote_completion_status($quote_id)
 {
     //module_cache::clear_cache();
     module_cache::clear('quote');
     $data = self::get_quote($quote_id);
     // save our cacheable items
     foreach (array('total_amount_invoicable') as $cacheable_item) {
         if (isset($data[$cacheable_item])) {
             // cacheable items can be the same name or prefixed with c_
             update_insert('quote_id', $quote_id, 'quote', array($cacheable_item => $data[$cacheable_item], "c_{$cacheable_item}" => $data[$cacheable_item]));
         }
     }
     $return_status = $data['status'];
     module_cache::clear('quote');
     return $return_status;
 }
Ejemplo n.º 8
0
 * Envato: 4ffca17e-861e-4921-86c3-8931978c40ca
 * Package Date: 2015-11-25 02:55:20 
 * IP Address: 67.79.165.254
 */
$autoreply_queue = array();
//set_time_limit(10);
// find all the mail setting accounts to check.
foreach (module_ticket::get_accounts() as $account) {
    $updated_tickets = module_ticket::import_email($account['ticket_account_id']);
    if (is_array($updated_tickets)) {
        $autoreply_queue = array_merge($autoreply_queue, $updated_tickets);
    }
}
imap_errors();
//print_r($autoreply_queue);
module_cache::clear('ticket');
foreach ($autoreply_queue as $ticket_id) {
    ob_start();
    handle_hook('ticket_sidebar', $ticket_id);
    // to get envato hook working quicker
    ob_end_clean();
    // we have to send the email to admin notifying them about this ticket too.
    // if this latest email came from an admin user (ie: the user is replying to a customer via email)
    // then we don't send_admin_alert or autoreply, we just send reply back to customer.
    $ticket_data = module_ticket::get_ticket($ticket_id);
    $last_ticket_message = module_ticket::get_ticket_message($ticket_data['last_ticket_message_id']);
    $admins_rel = module_ticket::get_ticket_staff_rel();
    // if the last email was from admin, send customer alert.
    if (isset($admins_rel[$last_ticket_message['from_user_id']])) {
        //        echo "sending a customer alert ";
        //        print_r($last_ticket_message);
Ejemplo n.º 9
0
 public static function clear_cache($cache_key = false)
 {
     if (!module_config::c('cache_enabled', 1)) {
         return;
     }
     if (_DEBUG_MODE && module_config::c('cache_debug', 0)) {
         module_debug::log(array('title' => 'Clear Cache', 'data' => "Key: {$cache_key}"));
     }
     if ($cache_key) {
         if (isset(self::$cache_store[$cache_key])) {
             unset(self::$cache_store[$cache_key]);
         }
     } else {
         // clear all
         self::$cache_store = array();
     }
 }
Ejemplo n.º 10
0
                }
                $item_ticket_count[$item_id]['count']++;
                $envato_count += $item['cost'];
            }
        } else {
            $item_id = '-1';
            if (!isset($item_ticket_count[$item_id])) {
                $item_ticket_count[$item_id] = array('envato_id' => $item_id, 'name' => 'No product', 'count' => 0, 'cost' => 0);
            }
            $item_ticket_count[$item_id]['count']++;
        }
    }
    if (mysql_num_rows($tickets) > 0) {
        mysql_data_seek($tickets, 0);
    }
    module_cache::put('ticket', 'envato_ticket_earning', $envato_count);
    //}
    function sort_envato_ticket_count($a, $b)
    {
        //return ($a['count']*$a['cost'])<=($b['count']*$b['cost']);
        return $a['count'] <= $b['count'];
    }
    uasort($item_ticket_count, 'sort_envato_ticket_count');
    foreach ($item_ticket_count as $i) {
        ?>
 <a href="?search[envato_item_id][]=<?php 
        echo $i['envato_id'];
        ?>
"><?php 
        echo htmlspecialchars($i['name']);
        ?>
Ejemplo n.º 11
0
 public function complete_plugin_installation($plugin_name)
 {
     global $plugins;
     $result = array('message' => '');
     $new_system_version = module_config::current_version();
     $fail = false;
     if (isset($plugins[$plugin_name])) {
         $result['message'] .= "Processing update: <span style='text-decoration:underline;'>" . $plugin_name . "</span> - Current Version: " . $plugins[$plugin_name]->get_plugin_version() . ".... ";
         ob_start();
         if ($version = $plugins[$plugin_name]->install_upgrade()) {
             $result['message'] .= '<span class="success_text">all good</span>';
             $new_system_version = max($version, $new_system_version);
             $plugins[$plugin_name]->init();
             // lol typo - oh well.
             $plugins[$plugin_name]->set_insatlled_plugin_version($version);
         } else {
             $fail = true;
             $result['message'] .= '<span class="error_text">failed</span> ';
         }
         $result['message'] .= ob_get_clean() . '<br/>';
         $result['message'] .= '<br/>';
         if ($fail) {
             $result['message'] .= _('Some things failed. Please go back and try again.');
         } else {
             $result['message'] .= '<strong>' . _l('Success! Everything worked.') . '</strong>';
             module_config::set_system_version($new_system_version);
             module_config::save_config('last_update', time());
         }
         if (isset($_SESSION['_message']) && count($_SESSION['_message'])) {
             $result['message'] .= '<br/>';
             $result['message'] .= implode('<br/>', $_SESSION['_message']);
             unset($_SESSION['_errors']);
         }
         if (isset($_SESSION['_errors']) && count($_SESSION['_errors'])) {
             $result['message'] .= '<br/>';
             $result['message'] .= implode('<br/>', $_SESSION['_errors']);
             unset($_SESSION['_errors']);
         }
     } else {
         if ($plugin_name == 'corefiles' || $plugin_name == 'database') {
         } else {
             $fail = true;
         }
     }
     // hack to clear db field cache:
     module_cache::clear('db');
     if (!$fail) {
         $result['success'] = 1;
     }
     return $result;
 }
Ejemplo n.º 12
0
											    <li class="footer">
												    <a href="<?php 
                                echo module_job::link_open(false);
                                ?>
"><?php 
                                _e('View All Jobs');
                                ?>
</a>
											    </li>
										    </ul>
									    </li>
								    <?php 
                            }
                            $job_todo_cache = ob_get_clean();
                            echo $job_todo_cache;
                            module_cache::put('job', 'job_todo_header_cache', $job_todo_cache);
                        }
                    }
                    ?>


						    <!-- User Account: style can be found in dropdown.less -->
						    <li class="dropdown user user-menu">
							    <?php 
                    $user = module_user::get_user(module_security::get_loggedin_id());
                    ?>

							    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
								    <i class="glyphicon glyphicon-user"></i>
								    <span><?php 
                    echo htmlspecialchars($user['name']);
Ejemplo n.º 13
0
 public static function remove_credit($customer_id, $credit, $note = false)
 {
     $customer_data = self::get_customer($customer_id);
     $customer_data['credit'] -= $credit;
     update_insert('customer_id', $customer_id, 'customer', array('credit' => $customer_data['credit']));
     module_cache::clear('customer');
     //self::add_history($customer_id,'Added '.dollar($credit).' credit to customers account.');
 }
Ejemplo n.º 14
0
 public function save_user($user_id, $data, $from_public = false)
 {
     $use_master_key = $this->get_contact_master_key();
     if ($from_public) {
         $user_id = 0;
     } else {
         if ($use_master_key && isset($data[$use_master_key]) && $data[$use_master_key]) {
             if (!module_user::can_i('edit', 'Contacts', 'Customer')) {
                 set_error('Unable to edit contacts.');
                 return false;
             }
         } else {
             if (!self::can_i('edit', 'Users', 'Config')) {
                 set_error('Unable to edit users.');
                 return false;
             }
         }
         $user_id = (int) $user_id;
     }
     $temp_user = array();
     if ($user_id > 0) {
         // check permissions
         $temp_user = $this->get_user($user_id, true, false);
         if (!$temp_user || $temp_user['user_id'] != $user_id || isset($temp_user['_perms'])) {
             $user_id = false;
         }
     }
     if (!$user_id && !$from_public) {
         if ($use_master_key && isset($data[$use_master_key]) && $data[$use_master_key]) {
             if (!module_user::can_i('create', 'Contacts', 'Customer')) {
                 set_error('Unable to create new contacts.');
                 return false;
             }
         } else {
             if (!self::can_i('create', 'Users', 'Config')) {
                 set_error('Unable to create new users.');
                 return false;
             }
         }
     } else {
         if ($user_id == 1 && module_security::get_loggedin_id() != 1) {
             set_error('Sorry only the administrator can modify this account');
         }
     }
     // check the customer id is valid assignment to someone who has these perms.
     if (!$from_public) {
         if (isset($data['customer_id']) && (int) $data['customer_id'] > 0) {
             $temp_customer = module_customer::get_customer($data['customer_id']);
             if (!$temp_customer || $temp_customer['customer_id'] != $data['customer_id']) {
                 unset($data['customer_id']);
             }
         }
         if (isset($data['vendor_id']) && (int) $data['vendor_id'] > 0) {
             $temp_vendor = module_vendor::get_vendor($data['vendor_id']);
             if (!$temp_vendor || $temp_vendor['vendor_id'] != $data['vendor_id']) {
                 unset($data['vendor_id']);
             }
         }
     }
     if (isset($data['password'])) {
         unset($data['password']);
     }
     // we do the password hash thing here.
     if (isset($data['password_new']) && strlen($data['password_new'])) {
         // an admin is trying to set the password for this account.
         // same permissions checks as on the user_admin_edit_login.php page
         if (!$user_id || isset($temp_user['password']) && !$temp_user['password'] || module_user::can_i('create', 'Users Passwords', 'Config') || isset($_REQUEST['reset_password']) && $_REQUEST['reset_password'] == module_security::get_auto_login_string($user_id)) {
             // we allow the admin to set a new password without typing in previous password.
             $data['password'] = $data['password_new'];
         } else {
             set_error('Sorry, no permissions to set a new password.');
         }
     } else {
         if ($user_id && isset($data['password_new1']) && isset($data['password_new2']) && strlen($data['password_new1'])) {
             // the user is trying to change their password.
             // only do this if the user has edit password permissions and their password matches.
             if (module_user::can_i('edit', 'Users Passwords', 'Config') || $user_id == module_security::get_loggedin_id()) {
                 if (isset($data['password_old']) && (md5($data['password_old']) == $temp_user['password'] || $data['password_old'] == $temp_user['password'])) {
                     // correct old password
                     // verify new password.
                     if ($data['password_new1'] == $data['password_new2']) {
                         $data['password'] = $data['password_new1'];
                     } else {
                         set_error('Verified password mismatch. Password unchanged.');
                     }
                 } else {
                     set_error('Old password does not match. Password unchanged.');
                 }
             } else {
                 set_error('No permissions to change passwords');
             }
         }
     }
     // and we finally hash our password
     if (isset($data['password']) && strlen($data['password']) > 0) {
         $data['password'] = md5($data['password']);
         // if you change md5 also change it in customer import.
         // todo - salt? meh.
     }
     $user_id = update_insert("user_id", $user_id, "user", $data);
     $use_master_key = $this->get_contact_master_key();
     // this will be customer_id or supplier_id
     if ($use_master_key && (isset($data[$use_master_key]) && $data[$use_master_key])) {
         if ($user_id) {
             if (isset($data['customer_primary']) && $data['customer_primary']) {
                 // update the customer/supplier to mark them as primary or not..
                 switch ($use_master_key) {
                     case 'customer_id':
                         module_customer::set_primary_user_id($data['customer_id'], $user_id);
                         break;
                     case 'vendor_id':
                         module_vendor::set_primary_user_id($data['vendor_id'], $user_id);
                         break;
                 }
             } else {
                 // check if this contact was the old customer/supplier primary and
                 switch ($use_master_key) {
                     case 'customer_id':
                         $customer_data = module_customer::get_customer($data['customer_id']);
                         if ($customer_data['primary_user_id'] == $user_id) {
                             module_customer::set_primary_user_id($data['customer_id'], 0);
                         }
                         break;
                     case 'vendor_id':
                         $vendor_data = module_vendor::get_vendor($data['vendor_id']);
                         if ($vendor_data['primary_user_id'] == $user_id) {
                             module_vendor::set_primary_user_id($data['vendor_id'], 0);
                         }
                         break;
                 }
             }
         }
     }
     if (!$from_public) {
         // hack for linked user accounts.
         if ($user_id && isset($data['link_customers']) && $data['link_customers'] == 'yes' && isset($data['link_user_ids']) && is_array($data['link_user_ids']) && isset($data['email']) && $data['email']) {
             $others = module_user::get_contacts(array('email' => $data['email']));
             foreach ($data['link_user_ids'] as $link_user_id) {
                 if (!(int) $link_user_id) {
                     continue;
                 }
                 if ($link_user_id == $user_id) {
                     continue;
                 }
                 // shouldnt happen
                 foreach ($others as $other) {
                     if ($other['user_id'] == $link_user_id) {
                         // success! they'renot trying to hack us.
                         $sql = "REPLACE INTO `" . _DB_PREFIX . "user_customer_rel` SET user_id = '" . (int) $link_user_id . "', customer_id = '" . (int) $other['customer_id'] . "', `primary` = " . (int) $user_id;
                         query($sql);
                         update_insert('user_id', $link_user_id, 'user', array('linked_parent_user_id' => $user_id));
                     }
                 }
             }
             update_insert('user_id', $user_id, 'user', array('linked_parent_user_id' => $user_id));
         }
         if ($user_id && isset($data['unlink']) && $data['unlink'] == 'yes') {
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_customer_rel` WHERE user_id = '" . (int) $user_id . "'";
             query($sql);
             update_insert('user_id', $user_id, 'user', array('linked_parent_user_id' => 0));
         }
         handle_hook("address_block_save", $this, "physical", "user", "user_id", $user_id);
         handle_hook("address_block_save", $this, "postal", "user", "user_id", $user_id);
         if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
             module_extra::save_extras('user', 'user_id', $user_id);
         }
         // find current role / permissions
         $user_data = $this->get_user($user_id);
         $previous_user_roles = $user_data['roles'];
         $re_save_role_perms = false;
         // hack to support only 1 role (we may support multi-role in the future)
         // TODO: check we have permissions to set this role id, otherwise anyone can set their own role.
         if (isset($_REQUEST['role_id'])) {
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_role` WHERE user_id = '" . (int) $user_id . "'";
             query($sql);
             if ((int) $_REQUEST['role_id'] > 0) {
                 if (!isset($previous_user_roles[$_REQUEST['role_id']])) {
                     $re_save_role_perms = (int) $_REQUEST['role_id'];
                 }
                 $_REQUEST['role'] = array($_REQUEST['role_id'] => 1);
             }
         }
         // save users roles (support for multi roles in future - but probably will never happen)
         if (isset($_REQUEST['role']) && is_array($_REQUEST['role'])) {
             foreach ($_REQUEST['role'] as $role_id => $tf) {
                 $this->add_user_to_role($user_id, $role_id);
             }
         }
         if ($re_save_role_perms) {
             // copy role permissiosn to user permissions
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_perm` WHERE user_id = " . (int) $user_id;
             query($sql);
             // update - we are not relying on these permissions any more.
             // if the user has a role assigned, we use those permissions period
             // we ignore all permissions in the user_perm table if the user has a role.
             // if the user doesn't have a role, then we use these user_perm permissions.
             /*$security_role = module_security::get_security_role($re_save_role_perms);
             		foreach($security_role['permissions'] as $security_permission_id => $d){
             			$sql = "INSERT INTO `"._DB_PREFIX."user_perm` SET user_id = ".(int)$user_id.", security_permission_id = '".(int)$security_permission_id."'";
             			foreach(module_security::$available_permissions as $perm){
             				$sql .= ", `".$perm."` = ".(int)$d[$perm];
             			}
             			query($sql);
             		}*/
         } else {
             if (isset($_REQUEST['permission']) && is_array($_REQUEST['permission'])) {
                 $sql = "DELETE FROM `" . _DB_PREFIX . "user_perm` WHERE user_id = '" . (int) $user_id . "'";
                 query($sql);
                 // update permissions for this user.
                 foreach ($_REQUEST['permission'] as $security_permission_id => $permissions) {
                     $actions = array();
                     foreach (module_security::$available_permissions as $permission) {
                         if (isset($permissions[$permission]) && $permissions[$permission]) {
                             $actions[$permission] = 1;
                         }
                     }
                     $sql = "REPLACE INTO `" . _DB_PREFIX . "user_perm` SET user_id = '" . (int) $user_id . "', security_permission_id = '" . (int) $security_permission_id . "' ";
                     foreach ($actions as $permission => $tf) {
                         $sql .= ", `" . mysql_real_escape_string($permission) . "` = 1";
                     }
                     query($sql);
                 }
             }
         }
         /*global $plugins;
         		if($user_id && isset($data['user_type_id']) && $data['user_type_id'] == 1 && $data['site_id']){
         			// update the site.
         			$plugins['site']->set_primary_user_id($data['site_id'],$user_id);
         		}else{
         			//this use isn't (or isnt any more) the sites primary user.
         			// unset this if he was the primary user before
         			$site_data = $plugins['site']->get_site($data['site_id']);
         			if(isset($site_data['primary_user_id']) && $site_data['primary_user_id'] == $user_id){
         				$plugins['site']->set_primary_user_id($data['site_id'],0);
         			}
         		}*/
         // save the company information if it's available
         if (class_exists('module_company', false) && module_company::can_i('edit', 'Company') && module_company::is_enabled() && module_user::can_i('edit', 'User')) {
             if (isset($_REQUEST['available_user_company']) && is_array($_REQUEST['available_user_company'])) {
                 $selected_companies = isset($_POST['user_company']) && is_array($_POST['user_company']) ? $_POST['user_company'] : array();
                 foreach ($_REQUEST['available_user_company'] as $company_id => $tf) {
                     if (!isset($selected_companies[$company_id]) || !$selected_companies[$company_id]) {
                         // remove user from this company
                         module_company::delete_user($company_id, $user_id);
                     } else {
                         // add user to this company (if they are not already existing)
                         module_company::add_user_to_company($company_id, $user_id);
                     }
                 }
             }
         }
     }
     module_cache::clear('user');
     return $user_id;
 }
Ejemplo n.º 15
0
 public function run_cron($debug = false)
 {
     // we only want to perform these cron actions if we're after a certain time of day
     // because we dont want to be generating these renewals and sending them at midnight, can get confusing
     $after_time = module_config::c('invoice_automatic_after_time', 7);
     $time_of_day = date('G');
     if ($time_of_day < $after_time) {
         if ($debug) {
             echo "Not performing automatic invoice operations until after {$after_time}:00 - it is currently {$time_of_day}:" . date('i') . "<br>\n";
         }
         return;
     }
     // find automaitic invoice overdues
     $sql = "SELECT * FROM `" . _DB_PREFIX . "invoice`  ";
     $sql .= " WHERE date_due != '0000-00-00' AND date_due <= '" . date('Y-m-d') . "' AND date_paid = '0000-00-00' AND date_cancel = '0000-00-00'";
     $invoice_items = qa($sql);
     if ($debug) {
         echo "Processing " . count($invoice_items) . " overdue invoices:  <br>\n";
     }
     foreach ($invoice_items as $invoice_item) {
         module_cache::clear('invoice');
         $invoice = module_invoice::get_invoice($invoice_item['invoice_id']);
         if ($invoice['overdue'] && $invoice['overdue_email_auto']) {
             if ($debug) {
                 echo "Processing overdue for invoice: " . module_invoice::link_open($invoice['invoice_id'], true) . " <br>\n";
             }
             if ($debug) {
                 echo " - last sent: " . $invoice['date_sent'] . " <br>\n";
             }
             if ($debug) {
                 echo " - due date: " . $invoice['date_due'] . " <br>\n";
             }
             if ($debug) {
                 echo " - now: " . date('Y-m-d') . " ( " . time() . " ) <br>\n";
             }
             // if you change this calculation make sure it is changed in the dashboard alerts above to
             $send_email_on = false;
             if ($invoice['date_sent'] && $invoice['date_sent'] != '0000-00-00' && strtotime($invoice['date_sent']) > strtotime($invoice['date_due'])) {
                 // we have sent a reminder already (todo: this isn't correct logic, fix it up so it can tell for sure if we have sent a reminder already or not (eg: look through email history table)
                 $last_invoice_sent = strtotime($invoice['date_sent']);
                 if (module_config::c('overdue_email_auto_days_repeat', 7) <= 0) {
                     continue;
                     // skip sendin repeat reminders.
                 }
                 $send_email_on = strtotime('+' . module_config::c('overdue_email_auto_days_repeat', 7) . ' days', $last_invoice_sent);
             } else {
                 if ($invoice['date_sent'] && $invoice['date_sent'] != '0000-00-00') {
                     $invoice_is_due = strtotime($invoice['date_due']);
                     $send_email_on = strtotime('+' . module_config::c('overdue_email_auto_days', 3) . ' days', $invoice_is_due);
                     if ($debug) {
                         echo module_config::c('overdue_email_auto_days', 3) . " days from " . $invoice['date_due'] . " is " . date('Y-m-d', $send_email_on) . "<br>\n";
                     }
                 } else {
                     // this invoice has not been sent yet, so we don't send an automated overdue notice.
                     // the user has to pick a "sent datE" before the system will send overdue notices.
                     if ($debug) {
                         echo " - NOT Sending Overdue Invoice Notice for " . module_invoice::link_open($invoice['invoice_id'], true) . " because it has no SENT DATE.<br>\n";
                     }
                     $send_email_on = false;
                 }
             }
             if ($invoice['date_sent'] && $invoice['date_sent'] != '0000-00-00' && date('Y-m-d', $send_email_on) == $invoice['date_sent']) {
                 if ($debug) {
                     echo " - NOT Sending Overdue Invoice Notice for " . module_invoice::link_open($invoice['invoice_id'], true) . " because it was last sent today already.<br>\n";
                 }
                 $send_email_on = false;
             }
             if ($send_email_on !== false && $debug) {
                 echo " - will send next invoice at: " . date('Y-m-d', $send_email_on) . " ( {$send_email_on} ) <br>\n";
             }
             if ($send_email_on !== false && $send_email_on <= strtotime(date('Y-m-d'))) {
                 if ($debug) {
                     echo " - Automatically Sending Overdue Invoice Notice for " . module_invoice::link_open($invoice['invoice_id'], true) . "<br>\n";
                 }
                 if ($debug) {
                     echo " - Emailing invoice to customer...";
                 }
                 if (module_invoice::email_invoice_to_customer($invoice['invoice_id'], $debug)) {
                     if ($debug) {
                         echo "sent successfully<br>\n";
                     }
                 } else {
                     echo "sending overdue invoice email failed for " . module_invoice::link_open($invoice['invoice_id'], true) . "<br>\n";
                 }
                 if ($debug) {
                     echo "<br>\n";
                 }
             }
         }
     }
     // find automatic invoice renewals
     $sql = "SELECT i.* FROM `" . _DB_PREFIX . "invoice` i ";
     $sql .= " WHERE i.date_renew != '0000-00-00'";
     $sql .= " AND i.date_create != '0000-00-00'";
     $sql .= " AND i.date_cancel = '0000-00-00'";
     $sql .= " AND i.date_renew <= '" . date('Y-m-d') . "'";
     $sql .= " AND (i.renew_invoice_id IS NULL OR i.renew_invoice_id = 0)";
     $sql .= " AND (i.renew_auto = 1)";
     $renew_invoices = qa($sql);
     foreach ($renew_invoices as $renew_invoice) {
         // time to automatically renew this invoice! woo!
         if ($debug) {
             echo "Automatically Renewing invoice " . module_invoice::link_open($renew_invoice['invoice_id'], true) . "<br>\n";
         }
         $invoice_data = module_invoice::get_invoice($renew_invoice['invoice_id']);
         if (module_config::c('invoice_auto_renew_only_paid_invoices', 1) && $invoice_data['total_amount_due'] > 0) {
             // invoice hasnt been paid, dont continue with renewl
             if ($debug) {
                 echo "NOT RENEWING INVOICE because it hasn't been paid yet !!! <br>\n";
             }
         } else {
             $new_invoice_id = $this->renew_invoice($renew_invoice['invoice_id']);
             if ($new_invoice_id) {
                 //module_cache::clear_cache();
                 if ($debug) {
                     echo "invoice Automatically Renewed: " . module_invoice::link_open($new_invoice_id, true) . "<br>\n";
                 }
                 if ($renew_invoice['renew_email']) {
                     if ($debug) {
                         echo "Emailing invoice to customer...";
                     }
                     if (module_invoice::email_invoice_to_customer($new_invoice_id, $debug)) {
                         if ($debug) {
                             echo "send successfully";
                         }
                     } else {
                         echo "sending renewed invoice email failed for " . module_invoice::link_open($new_invoice_id, true) . "<br>\n";
                     }
                     if ($debug) {
                         echo "<br>\n";
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 16
0
 public function handle_hook($hook, &$calling_module = false)
 {
     switch ($hook) {
         case "home_alerts":
             $alerts = array();
             if (module_config::c('change_request_alerts', 1) && class_exists('module_website', false)) {
                 $cache_key = "home_alerts_" . module_security::get_loggedin_id();
                 $cache_timeout = module_config::c('cache_objects', 60);
                 if ($alerts = module_cache::get('change_request', $cache_key)) {
                     return $alerts;
                 }
                 // find any open change requests for all customers.
                 $websites = module_website::get_websites(array(), array('columns' => 'u.website_id'));
                 // this gets websites we have permission to view.
                 if (count($websites) > 0) {
                     $website_ids = array();
                     foreach ($websites as $website) {
                         $website_ids[] = $website['website_id'];
                     }
                     // build a query to find all new change requests for websitse we have access to
                     $sql = "SELECT * FROM `" . _DB_PREFIX . "change_request` cr WHERE `website_id` IN (" . implode(', ', $website_ids) . ") AND `status` = " . _CHANGE_REQUEST_STATUS_NEW;
                     $website_requests = qa($sql);
                     foreach ($website_requests as $website_request) {
                         $alert_res = process_alert($website_request['date_created'], _l('Change Request'));
                         if ($alert_res) {
                             $alert_res['link'] = module_website::link_open($website_request['website_id'], false);
                             $alert_res['name'] = $website_request['url'];
                             $alerts[] = $alert_res;
                         }
                     }
                     /*$website_requests = self::get_change_requests(array(
                                                 'website_id'=>$website['website_id'],
                                                 'status'=>_CHANGE_REQUEST_STATUS_NEW,
                                             ));
                                             foreach($website_requests as $website_request){
                     
                                                 $alert_res = process_alert($website_request['date_created'], _l('Change Request'));
                                                 if($alert_res){
                                                     $alert_res['link'] = module_website::link_open($website['website_id'],false);
                                                     $alert_res['name'] = $website_request['url'];
                                                     $alerts[] = $alert_res;
                                                 }
                     
                                             }*/
                 }
                 module_cache::put('change_request', $cache_key, $alerts, $cache_timeout);
             }
             return $alerts;
     }
 }
Ejemplo n.º 17
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;
 }
Ejemplo n.º 18
0
 public static function bulk_handle_status()
 {
     if (isset($_REQUEST['bulk_action']) && isset($_REQUEST['bulk_action']['status_resolved']) && $_REQUEST['bulk_action']['status_resolved'] == 'yes' && isset($_REQUEST['bulk_change_status_id']) && $_REQUEST['bulk_change_status_id'] > 0) {
         // confirm deletion of these tickets:
         $ticket_ids = isset($_REQUEST['bulk_operation']) && is_array($_REQUEST['bulk_operation']) ? $_REQUEST['bulk_operation'] : array();
         foreach ($ticket_ids as $ticket_id => $k) {
             if ($k != 'yes') {
                 unset($ticket_ids[$ticket_id]);
             } else {
                 $ticket_ids[$ticket_id] = '#' . self::ticket_number($ticket_id);
             }
         }
         if (count($ticket_ids) > 0) {
             foreach ($ticket_ids as $ticket_id => $ticket_number) {
                 update_insert('ticket_id', $ticket_id, 'ticket', array('status_id' => $_REQUEST['bulk_change_status_id']));
             }
             module_cache::clear('ticket');
             $statuses = self::get_statuses();
             set_message(_l("%s tickets marked as %s", count($ticket_ids), $statuses[$_REQUEST['bulk_change_status_id']]));
             //redirect_browser(self::link_open(false));
         }
     }
 }