/**
  * generate pdf
  *
  * @param Invoice $invoice
  * @return InvoicePdfGenerator
  */
 function preparePDF(&$invoice)
 {
     $owner_company = get_owner_company();
     $generator = new InvoicePdfGenerator($invoice, $owner_company);
     $generator->paper_format = ConfigOptions::getValue('invoicing_pdf_paper_format');
     $generator->paper_orientation = ConfigOptions::getValue('invoicing_pdf_paper_orientation');
     $generator->setHeaderFontColor('#' . ConfigOptions::getValue('invoicing_pdf_header_text_color'));
     $generator->setBodyFontColor('#' . ConfigOptions::getValue('invoicing_pdf_page_text_color'));
     $generator->setBorderColor('#' . ConfigOptions::getValue('invoicing_pdf_border_color'));
     $generator->setBackgroundColor('#' . ConfigOptions::getValue('invoicing_pdf_background_color'));
     $generator->FontFamily = 'freesans';
     return $generator;
 }
 /**
  * Install this module
  *
  * @param void
  * @return boolean
  */
 function install()
 {
     // invoices
     $this->createTable('invoices', array('id smallint(5) unsigned NOT NULL auto_increment', 'company_id smallint(5) unsigned NOT NULL default \'0\'', 'project_id smallint(5) unsigned default NULL', 'currency_id tinyint(4) NOT NULL default \'0\'', 'language_id tinyint(3) NOT NULL default \'0\'', 'number varchar(50) NOT NULL', 'company_name varchar(50) NOT NULL', 'company_address text', 'comment varchar(255) default NULL', 'note text', 'status tinyint(4) NOT NULL default \'0\'', 'issued_on date default NULL', 'issued_by_id int(11) default NULL', 'issued_by_name varchar(100) default NULL', 'issued_by_email varchar(150) default NULL', 'issued_to_id int(11) default NULL', 'due_on date default NULL', 'closed_on datetime default NULL', 'closed_by_id int(11) default NULL', 'closed_by_name varchar(100) default NULL', 'closed_by_email varchar(150) default NULL', 'created_on datetime default NULL', 'created_by_id int(10) unsigned default NULL', 'created_by_name varchar(100) default NULL', 'created_by_email varchar(150) default NULL'), 'PRIMARY KEY  (id)');
     // Invoice Items
     $this->createTable('invoice_items', array('id int(11) unsigned NOT NULL auto_increment', 'invoice_id smallint(5) unsigned NOT NULL default \'0\'', 'position int(11) NOT NULL', 'tax_rate_id tinyint(3) unsigned NOT NULL default \'0\'', 'description varchar(255) NOT NULL', 'quantity DECIMAL(13,3) unsigned NOT NULL default \'1\'', 'unit_cost DECIMAL(13,3) NOT NULL default \'0.00\''), array('PRIMARY KEY  (id)', 'KEY invoice_id (invoice_id,position)'));
     $this->createTable('invoice_item_templates', array('id int(11) unsigned NOT NULL auto_increment', 'tax_rate_id tinyint(3) unsigned NOT NULL default \'0\'', 'description varchar(255) NOT NULL', 'quantity DECIMAL(13,3) unsigned NOT NULL default \'1\'', 'unit_cost DECIMAL(13,3) NOT NULL default \'0.00\'', "position int(11) NOT NULL default '0'"), array('PRIMARY KEY  (id)'));
     // Invoice payments
     $this->createTable('invoice_payments', array('id int(10) unsigned NOT NULL auto_increment', 'invoice_id smallint(5) unsigned NOT NULL', 'amount DECIMAL(13,3) NOT NULL', 'paid_on date NOT NULL', 'comment text', 'created_on datetime default NULL', 'created_by_id int(10) unsigned default NULL', 'created_by_name varchar(100) default NULL', 'created_by_email varchar(150) default NULL'), array('PRIMARY KEY  (id)', 'KEY invoice_id (invoice_id)'));
     // Invoice note templates
     $this->createTable('invoice_note_templates', array('id int(10) unsigned NOT NULL auto_increment', 'position int(11) NOT NULL', 'name varchar(150) default NULL', 'content text'), 'PRIMARY KEY  (id)');
     // Invoice time records
     $this->createTable('invoice_time_records', array('invoice_id smallint(5) unsigned NOT NULL', 'item_id int(10) unsigned NOT NULL', 'time_record_id int(10) unsigned NOT NULL'), 'PRIMARY KEY  (invoice_id,time_record_id)');
     // invoice_tax_rates
     $this->createTable('tax_rates', array('id tinyint(3) unsigned NOT NULL auto_increment', 'name varchar(50) NOT NULL', 'percentage DECIMAL(6,3) NOT NULL'), 'PRIMARY KEY  (id)');
     db_execute("INSERT INTO " . TABLE_PREFIX . "tax_rates (id, name, percentage) VALUES\n        (1, 'VAT', 17.50);");
     $this->createTable('currencies', array('id smallint(6) NOT NULL auto_increment', 'name varchar(50) NOT NULL', 'code varchar(3) NOT NULL', 'default_rate DECIMAL(13,3) unsigned NOT NULL', 'is_default tinyint(1) unsigned NOT NULL default \'0\''), array('PRIMARY KEY  (id)'));
     db_execute("INSERT INTO " . TABLE_PREFIX . "currencies (id, name, code, default_rate, is_default) VALUES\n        (1, 'Euro', 'EUR', 1, 0),\n        (2, 'US Dollar', 'USD', 1, 1),\n        (3, 'British Pound', 'GBP', 1, 0),\n        (4, 'Japanese Yen', 'JPY', 1, 0)");
     // config options
     $this->addConfigOption('prefered_currency', SYSTEM_CONFIG_OPTION, null);
     $this->addConfigOption('invoicing_number_pattern', SYSTEM_CONFIG_OPTION, ':invoice_in_year/:current_year');
     $this->addConfigOption('invoicing_number_date_counters', SYSTEM_CONFIG_OPTION, null);
     // create and prepopulate company identity
     $owner_company = get_owner_company();
     $owner_company_address = $owner_company->getConfigValue('office_address');
     $this->addConfigOption('invoicing_company_name', SYSTEM_CONFIG_OPTION, $owner_company->getName());
     $this->addConfigOption('invoicing_company_details', SYSTEM_CONFIG_OPTION, $owner_company_address);
     // default PDF settings
     $this->addConfigOption('invoicing_pdf_paper_format', SYSTEM_CONFIG_OPTION, 'A4');
     $this->addConfigOption('invoicing_pdf_paper_orientation', SYSTEM_CONFIG_OPTION, 'Portrait');
     $this->addConfigOption('invoicing_pdf_header_text_color', SYSTEM_CONFIG_OPTION, '000000');
     $this->addConfigOption('invoicing_pdf_page_text_color', SYSTEM_CONFIG_OPTION, '000000');
     $this->addConfigOption('invoicing_pdf_border_color', SYSTEM_CONFIG_OPTION, '000000');
     $this->addConfigOption('invoicing_pdf_background_color', SYSTEM_CONFIG_OPTION, 'FFFFFF');
     // email templates
     $this->addEmailTemplate('issue', "Invoice #:invoice_number has been issued", "<p>Hi,</p>\n<p><a href=\":issued_by_url\">:issued_by_name</a> just issued invoice <b>#:invoice_number</b> to you. Access <a href=\":invoice_url\">invoice details here</a> or <a href=\":pdf_url\">download PDF version here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('issued_by_name', 'issued_by_url', 'invoice_number', 'invoice_url', 'pdf_url'));
     $this->addEmailTemplate('billed', "Invoice #:invoice_number has been billed", "<p>Hi,</p>\n<p><a href=\":closed_by_url\">:closed_by_name</a> just marked invoice <b>#:invoice_number</b> as billed. Access <a href=\":invoice_url\">invoice details and payments here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('closed_by_name', 'closed_by_url', 'invoice_number', 'invoice_url'));
     $this->addEmailTemplate('cancel', "Invoice #:invoice_number has been canceled", "<p>Hi,</p>\n<p><a href=\":closed_by_url\">:closed_by_name</a> just canceled invoice <b>#:invoice_number</b>. Access <a href=\":invoice_url\">invoice details here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('closed_by_name', 'closed_by_url', 'invoice_number', 'invoice_url'));
     recursive_mkdir(WORK_PATH . '/invoices', 0777, WORK_PATH);
     return parent::install();
 }
 /**
  * Constructor
  *
  * @param Request $request
  * @return ApplicationController
  */
 function __construct($request)
 {
     parent::__construct($request);
     // Set detault layout for application pages
     $this->setLayout(array('module' => SYSTEM_MODULE, 'layout' => 'wireframe'));
     // Get Smarty instance... We need it
     $this->smarty =& Smarty::instance();
     // Load and init owner company
     $this->owner_company = get_owner_company();
     if (instance_of($this->owner_company, 'Company')) {
         cache_set('owner_company', $this->owner_company);
     } else {
         $this->httpError(HTTP_ERR_NOT_FOUND, 'Owner company is not defined');
     }
     // if
     $this->application =& application();
     $this->authentication =& Authentication::instance();
     $this->logged_user =& $this->authentication->provider->getUser();
     $this->wireframe =& Wireframe::instance();
     $this->wireframe->page_company = $this->owner_company;
     $this->theme_name = instance_of($this->logged_user, 'User') ? UserConfigOptions::getValue('theme', $this->logged_user) : ConfigOptions::getValue('theme');
     $this->smarty->assign(array('root_url' => ROOT_URL, 'assets_url' => ASSETS_URL));
     // Maintenance mode
     if (ConfigOptions::getValue('maintenance_enabled')) {
         if (instance_of($this->logged_user, 'User') && $this->logged_user->isAdministrator()) {
             $this->wireframe->addPageMessage(lang('System is in maintenance mode and can be used by administrators only. <a href=":url">Click here</a> to turn off maintenance mode', array('url' => assemble_url('admin_settings_maintenance'))), 'warning');
         } else {
             $additional_error_info = ConfigOptions::getValue('maintenance_message');
             if ($additional_error_info) {
                 $additional_error_info .= "\n\n";
             }
             // if
             $additional_error_info .= lang('When system is in maintenance mode, administrators can log in and access the system') . ": " . assemble_url('login');
             $this->smarty->assign('additional_error_info', $additional_error_info);
             if ($this->restrict_access_in_maintenance_mode) {
                 $this->httpError(503);
             }
             // if
         }
         // if
     }
     // if
     // Check permissions
     if ($this->login_required && !instance_of($this->logged_user, 'User')) {
         // If async don't redirect to loging, just server proper HTTP code
         if ($this->request->isAsyncCall()) {
             $this->httpError(HTTP_ERR_UNAUTHORIZED, null, true, true);
             // Not async? Redirect to login with extracted route data...
         } else {
             $params = array();
             if ($request->matched_route != 'login') {
                 $params['re_route'] = $request->matched_route;
                 foreach ($this->request->url_params as $k => $v) {
                     if ($k == 'module' || $k == 'controller' || $k == 'action') {
                         continue;
                     }
                     // if
                     $params["re_{$k}"] = $v;
                 }
                 // foreach
             }
             // if
             $this->redirectTo($this->login_route, $params);
         }
         // if
     }
     // if
     if (instance_of($this->logged_user, 'User') && !$this->logged_user->getSystemPermission('system_access')) {
         $this->authentication->provider->logUserOut();
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $loaded_modules = $this->application->getModules();
     $assets_query_string = 'v=' . $this->application->version . '&modules=';
     foreach ($loaded_modules as $loaded_module) {
         $assets_query_string .= $loaded_module->getName() . ',';
     }
     // foreach
     $this->smarty->assign(array('api_status' => API_STATUS, 'application' => $this->application, 'owner_company' => $this->owner_company, 'authentication' => $this->authentication, 'logged_user' => $this->logged_user, 'request' => $this->request, 'theme_name' => $this->theme_name, 'request_time' => $this->request_time, 'loaded_modules' => $this->application->getModules(), 'captcha_url' => ROOT_URL . '/captcha.php?id=' . md5(time()), 'assets_query_string' => $assets_query_string, 'js_disabled_url' => assemble_url('js_disabled')));
     $this->smarty->assign_by_ref('wireframe', $this->wireframe);
     js_assign(array('homepage_url' => ROOT_URL, 'assets_url' => ASSETS_URL, 'indicator_url' => get_image_url('indicator.gif'), 'big_indicator_url' => get_image_url('indicator_big.gif'), 'ok_indicator_url' => get_image_url('ok_indicator.gif'), 'warning_indicator_url' => get_image_url('warning_indicator.gif'), 'error_indicator_url' => get_image_url('error_indicator.gif'), 'pending_indicator_url' => get_image_url('pending_indicator.gif'), 'url_base' => URL_BASE, 'keep_alive_interval' => KEEP_ALIVE_INTERVAL, 'refresh_session_url' => assemble_url('refresh_session'), 'jump_to_project_url' => assemble_url('jump_to_project_widget'), 'quick_add_url' => assemble_url('quick_add'), 'path_info_through_query_string' => PATH_INFO_THROUGH_QUERY_STRING, 'image_picker_url' => assemble_url('image_picker'), 'copyright_removed' => LICENSE_COPYRIGHT_REMOVED, 'custom_tabs_manager' => assemble_url('custom_tabs_manager'), 'add_milestone_url' => assemble_url('project_milestones_add', array('project_id' => '--PROJECT_ID--')), 'add_checklist_url' => assemble_url('project_checklists_add', array('project_id' => '--PROJECT_ID--')), 'add_discussion_url' => assemble_url('project_discussions_add', array('project_id' => '--PROJECT_ID--')), 'add_file_url' => assemble_url('project_files_upload', array('project_id' => '--PROJECT_ID--')), 'add_page_url' => assemble_url('project_pages_add', array('project_id' => '--PROJECT_ID--')), 'add_ticket_url' => assemble_url('project_tickets_add', array('project_id' => '--PROJECT_ID--')), 'add_timerecord_url' => assemble_url('project_time_add', array('project_id' => '--PROJECT_ID--')), 'attachment_rename_url' => assemble_url('attachment_rename', array('project_id' => '--PROJECT_ID--', 'attachment_id' => '--ATTACHMENT_ID--')), 'attachment_copy_to_url' => assemble_url('attachment_copy_to', array('project_id' => '--PROJECT_ID--', 'attachment_id' => '--ATTACHMENT_ID--')), 'attachment_move_to_url' => assemble_url('attachment_move_to', array('project_id' => '--PROJECT_ID--', 'attachment_id' => '--ATTACHMENT_ID--')), 'image_uploader_url' => assemble_url('image_uploader'), 'render_comments_url' => assemble_url('render_comments'), 'move_task_url' => assemble_url('project_task_move', array('project_id' => '--PROJECT_ID--', 'task_id' => '--TASK_ID--')), 'get_collection_url' => assemble_url('collection'), 'quick_task_reminder_url' => assemble_url('project_task_quickreminder', array('project_id' => '--PROJECT_ID--', 'task_id' => '--TASK_ID--')), 'convert_to_ticket_url' => assemble_url('project_object_convert_to_ticket', array('project_id' => '--PROJECT_ID--', 'object_id' => '--OBJECT_ID--')), 'convert_to_milestone_url' => assemble_url('project_object_convert_to_milestone', array('project_id' => '--PROJECT_ID--', 'object_id' => '--OBJECT_ID--')), 'convert_to_page_url' => assemble_url('project_object_convert_to_page', array('project_id' => '--PROJECT_ID--', 'object_id' => '--OBJECT_ID--')), 'snooze_task_url' => assemble_url('project_task_snooze', array('project_id' => '--PROJECT_ID--', 'task_id' => '--TASK_ID--'))));
     if ($this->logged_user) {
         $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
         mysql_select_db(DB_NAME);
         if (!empty($_SESSION['pg_ttl'])) {
             mysql_query("update healingcrystals_user_visited_pages set title='" . mysql_real_escape_string($_SESSION['pg_ttl']) . "' where user_id='" . $this->logged_user->getId() . "' and access_time='" . date('Y-m-d H:i:s', $_SESSION['temp_time']) . "'");
         }
         $current_url = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
         $pos = strpos($_SERVER['QUERY_STRING'], '%2F');
         if ($pos !== false) {
             $max_pages_count_per_user = 50;
             //require_once SMARTY_PATH . '/plugins/function.page_title.php';
             //$current_page_title = smarty_function_page_title(array('default' => 'Projects'));
             //$current_page_title = PageConstruction::getPageTitle();
             $_SESSION['temp_time'] = time();
             mysql_query("insert into healingcrystals_user_visited_pages (user_id, page_url, title, access_time) values ('" . $this->logged_user->getId() . "', '" . $current_url . "', '', '" . date('Y-m-d H:i:s', $_SESSION['temp_time']) . "')");
             //mysql_query("insert into healingcrystals_user_visited_pages (user_id, page_url, title, access_time) values ('" . $this->logged_user->getId() . "', '" . $current_url . "', '', now())");
             $query = "select count(*) as count from healingcrystals_user_visited_pages where user_id='" . $this->logged_user->getId() . "'";
             $result = mysql_query($query);
             $info = mysql_fetch_assoc($result);
             $current_count = $info['count'];
             if ($current_count > $max_pages_count_per_user) {
                 $querries = array();
                 $query = "select * from healingcrystals_user_visited_pages where user_id='" . $this->logged_user->getId() . "' order by access_time limit 0, " . ($current_count - $max_pages_count_per_user);
                 $result = mysql_query($query);
                 while ($info = mysql_fetch_assoc($result)) {
                     $querries[] = "delete from healingcrystals_user_visited_pages where user_id='" . $this->logged_user->getId() . "' and page_url='" . $info['page_url'] . "' and access_time='" . $info['access_time'] . "'";
                 }
             }
             foreach ($querries as $query) {
                 mysql_query($query);
             }
         }
         $_SESSION['pg_ttl'] = '';
         mysql_close($link);
     }
 }
 /**
  * Create new comment
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->wireframe->print_button = false;
     $active_object = ProjectObjects::findById($this->request->getId('parent_id'));
     if (!instance_of($active_object, 'ProjectObject')) {
         $this->httpError(HTTP_ERR_NOT_FOUND, null, true, $this->request->isApiCall());
     }
     // if
     if (!$active_object->canComment($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN, null, true, $this->request->isApiCall());
     }
     // if
     $active_object->prepareProjectSectionBreadcrumb($this->wireframe);
     $this->wireframe->addBreadCrumb($active_object->getName(), $active_object->getViewUrl());
     if (!$active_object->canComment($this->logged_user)) {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_FORBIDDEN, null, true, true);
         } else {
             flash_error('Parent object not found');
             $this->redirectToReferer($this->active_project->getOverviewUrl());
         }
         // if
     }
     // if
     $comment_data = $this->request->post('comment');
     $this->smarty->assign(array('active_object' => $active_object, 'page_tab' => $active_object->getProjectTab(), 'comment_data' => $comment_data, 'recent_comments' => Comments::findRecentObject($active_object, 5, STATE_VISIBLE, $this->logged_user->getVisibility())));
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $complete_parent_object = (bool) array_var($comment_data, 'complete_parent_object');
         $this->active_comment = new Comment();
         $this->active_comment->log_activities = false;
         if ($complete_parent_object) {
             $this->active_comment->send_notification = false;
         }
         // if
         attach_from_files($this->active_comment, $this->logged_user);
         $this->active_comment->setAttributes($comment_data);
         $this->active_comment->setParent($active_object);
         $this->active_comment->setProjectId($this->active_project->getId());
         $this->active_comment->setState(STATE_VISIBLE);
         $this->active_comment->setVisibility($active_object->getVisibility());
         if (trim($this->active_comment->getCreatedByName()) == '' || trim($this->active_comment->getCreatedByEmail()) == '') {
             $this->active_comment->setCreatedBy($this->logged_user);
         }
         // if
         $save = $this->active_comment->save();
         if ($save && !is_error($save)) {
             $active_object->subscribe($this->logged_user);
             $activity = new NewCommentActivityLog();
             $activity->log($this->active_comment, $this->logged_user);
             if ($complete_parent_object && $active_object->canChangeCompleteStatus($this->logged_user)) {
                 $active_object->complete($this->logged_user, $this->active_comment->getFormattedBody(true));
             }
             // if
             db_commit();
             $this->active_comment->ready();
             //BOF: mod
             $subscribers_to_notify = array_var($comment_data, 'subscribers_to_notify');
             $action_request_user_id = array_var($comment_data, 'action_request');
             //$priority_actionrequest = array_var($comment_data, 'priority_actionrequest');
             //BOF:mod 20110517
             if ($complete_parent_object) {
                 $subscribers_to_notify = array();
                 $action_request_user_id = array();
             }
             //EOF:mod 20110517
             //BOF:mod 20110719
             /*
             //EOF:mod 20110719
             if (!empty($action_request_user_id)){
                 $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 mysql_select_db(DB_NAME);
                 foreach ($action_request_user_id as $id){
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
             						$result = mysql_query($query);
             						if (mysql_num_rows($result)){
                         $query = "update healingcrystals_assignments_action_request set is_action_request='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                         mysql_query($query);
             						} else {
                         $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added) values ('" . $id . "', '1', '0', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                         mysql_query($query);
                     }
                 }
             
                 foreach($priority_actionrequest as $val){
                     $temp = explode('_', $val);
             						list($temp_user_id, $priority) = $temp;
             						if (in_array($temp_user_id, $action_request_user_id)){
                         $query = "update healingcrystals_assignments_action_request set priority_actionrequest='" . $priority . "' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                         mysql_query($query);
             						}
                 }
                 mysql_close($link);
             }
             //BOF:mod 20110719
             */
             //EOF:mod 20110719
             //BOF:mod 20110719
             //$action_request_user_id = array();
             //if (!empty($priority_actionrequest)){
             $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             mysql_select_db(DB_NAME);
             if (!empty($action_request_user_id)) {
                 //foreach($priority_actionrequest as $val){
                 foreach ($action_request_user_id as $val) {
                     //$temp = explode('_', $val);
                     //list($temp_user_id, $priority) = $temp;
                     $temp_user_id = $val;
                     $priority = '0';
                     //if ((int)$priority>-10){
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                     $result = mysql_query($query, $link);
                     if (mysql_num_rows($result)) {
                         $query1 = "update healingcrystals_assignments_action_request set is_action_request='1', priority_actionrequest='" . $priority . "' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                         mysql_query($query1, $link);
                     } else {
                         $query1 = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added, priority_actionrequest) values ('" . $temp_user_id . "', '1', '0', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now(), '" . $priority . "')";
                         mysql_query($query1, $link);
                     }
                     //$action_request_user_id[] = $temp_user_id;
                     $task = new Task();
                     $task->setProjectId(TASK_LIST_PROJECT_ID);
                     $task->setParentId(Page::getTaskPageIdForUser($val));
                     $task->setParentType('Page');
                     $task->setCreatedBy($this->logged_user);
                     $task->setVisibility(VISIBILITY_NORMAL);
                     $task->setState(STATE_VISIBLE);
                     $task_body = '';
                     $parent = $this->active_comment->getParent();
                     $url = $parent->getViewUrl() . '#comment' . $this->active_comment->getId();
                     $comment_body = $this->active_comment->getBody();
                     $comment_body = strip_tags($comment_body);
                     //$task_body = substr($comment_body, 0, 10) . '.. <br/><a href="' . $url . '">View Task in Full</a>';
                     if (strlen($comment_body) > 525) {
                         $task_body .= substr($comment_body, 0, 525) . '..';
                     } else {
                         $task_body .= $comment_body;
                     }
                     $task_body .= '<br/><a href="' . $url . '">View Task in Full</a>';
                     $attachments = $this->active_comment->getAttachments();
                     if (is_foreachable($attachments)) {
                         $task_body .= '<br/>Attachments:<br/>';
                         foreach ($attachments as $attachment) {
                             $task_body .= '<a href="' . $attachment->getViewUrl() . '">' . $attachment->getName() . '</a><br/>';
                         }
                     }
                     $task->setBody($task_body);
                     $savetask = $task->save();
                     if ($savetask && !is_error($savetask)) {
                         $task->ready();
                         mysql_query("insert into actionrequests_to_tasklist (comment_id, user_id, type, object_id) values ('" . $this->active_comment->getId() . "', '" . $temp_user_id . "', 'Task', '" . $task->getId() . "')");
                     }
                     //}
                 }
             }
             //EOF:mod 20110719
             if (!empty($subscribers_to_notify)) {
                 //BOF:task_1260
                 /*
                                     //EOF:task_1260
                                     mysql_query("update healingcrystals_assignments_action_request set is_fyi='0' where object_id='" . $active_object->getId() . "'");
                 if (!empty($subscribers_to_notify)){
                 	$temp = $subscribers_to_notify;
                 	foreach($temp as $id){
                 		$query = "select * from healingcrystals_assignments_action_request where object_id='" . $active_object->getId() . "' and user_id='" . $id . "'";
                 		$result = mysql_query($query, $link);
                 		if (mysql_num_rows($result)){
                 			mysql_query("update healingcrystals_assignments_action_request set is_fyi='1' where user_id='" . $id . "' and object_id='" . $active_object->getId() . "'");
                 		} else {
                 			mysql_query("insert into healingcrystals_assignments_action_request (user_id, object_id, is_fyi) values ('" . $id . "', '" . $active_object->getId() . "', '1')");
                 		}
                 	}
                 }
                 mysql_query("delete from healingcrystals_assignments_action_request where object_id='" . $active_object->getId() . "' and is_action_request='0' and is_fyi='0'");
                 //BOF:task_1260
                 */
                 foreach ($subscribers_to_notify as $id) {
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                     $result = mysql_query($query);
                     if (mysql_num_rows($result)) {
                         $query = "update healingcrystals_assignments_action_request set is_fyi='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                         mysql_query($query);
                     } else {
                         $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added) values ('" . $id . "', '0', '1', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                         mysql_query($query);
                     }
                 }
                 //EOF:task_1260
             }
             //shawn wants to fire emails for only action request users and not for FYI users
             // for this, $subscribers_to_notify is set to $action_request_user_id, which will
             // take care of any assignments that were made above the code : 22-MAR-2011
             //BOF:mod 20110623
             $fyi_users = $subscribers_to_notify;
             $fyi_to = '';
             //EOF:mod 20110623
             $subscribers_to_notify = $action_request_user_id;
             //BOF:mod
             $email_to_user_ids = array_var($comment_data, 'email');
             $emailed_to = '';
             foreach ($email_to_user_ids as $user_id) {
                 $temp_user = new User($user_id);
                 //BOF:mod 20130429
                 /*
                 //EOF:mod 20130429
                 					$emailed_to .= $temp_user->getName() . ', ';
                 //BOF:mod 20130429
                 */
                 //EOF:mod 20130429
                 $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $user_id . "'";
                 $result = mysql_query($query);
                 if (mysql_num_rows($result)) {
                     $query = "update healingcrystals_assignments_action_request set marked_for_email='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $user_id . "'";
                     mysql_query($query);
                 } else {
                     $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, marked_for_email, selected_by_user_id, comment_id, date_added) values ('" . $user_id . "', '0', '0', '1', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                     mysql_query($query);
                 }
             }
             reset($email_to_user_ids);
             //EOF:mod
             if (!empty($subscribers_to_notify)) {
                 //$subscribers_to_notify = implode(',', $subscribers_to_notify);
                 //mysql_query("insert into healingcrystals_testing (query, fired_at) values ('" . $subscribers_to_notify . "', now())");
                 $notified_to = '';
                 //$subscribers = explode(',', $subscribers_to_notify);
                 $subscribers = $subscribers_to_notify;
                 $all_subscribers = $active_object->getSubscribers();
                 $excluded = array();
                 $included = array();
                 //$excluded_temp = array();
                 //$included_temp = array();
                 $subscribers_name = '';
                 foreach ($all_subscribers as $reg_subscriber) {
                     $subscribers_name .= $reg_subscriber->getName() . "<br/>";
                     $subscriber_excluded = true;
                     //if ($this->logged_user->getId()!=$reg_subscriber->getId()){
                     foreach ($subscribers as $subscriber_id) {
                         $subscriber_id = trim($subscriber_id);
                         if ($reg_subscriber->getId() == $subscriber_id) {
                             $included[] = $reg_subscriber;
                             //BOF:mod 20130429
                             /*
                             //EOF:mod 20130429
                             								$notified_to .= $reg_subscriber->getName() . ', ';
                             //BOF:mod 20130429
                             */
                             //EOF:mod 20130429
                             //$included_temp[] = $reg_subscriber->getId();
                             $subscriber_excluded = false;
                             //$subscribers_name .= $reg_subscriber->getName() . "<br/>";
                             break;
                         }
                     }
                     //BOF:mod 20110623
                     foreach ($fyi_users as $fyi_user_id) {
                         $fyi_user_id = trim($fyi_user_id);
                         if ($reg_subscriber->getId() == $fyi_user_id) {
                             //BOF:mod 20130429
                             /*
                             //EOF:mod 20130429
                             								$fyi_to .= $reg_subscriber->getName() . ', ';
                             //BOF:mod 20130429
                             */
                             //EOF:mod 20130429
                             break;
                         }
                     }
                     //EOF:mod 20110623
                     //}
                     if ($subscriber_excluded) {
                         $excluded[] = $reg_subscriber->getId();
                         //$excluded_temp[] = $reg_subscriber->getId();
                     }
                 }
                 //$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 //mysql_select_db(DB_NAME);
                 //mysql_query("insert into healingcrystals_testing (query, fired_at) values ('" . implode('|', $included_temp) . ' = ' . implode('|', $excluded_temp) . "', now())");
                 //mysql_close($link);
                 //BOF:mod 20110517
                 //if (count($included)){
                 if (!$complete_parent_object && count($included)) {
                     //EOF:mod 20110517
                     //BOF:mod 20110623
                     //$notified_to = '<br/><br/>Notification emailed to: ' . substr($notified_to, 0, -2);
                     //$this->active_comment->setBody($this->active_comment->getBody() . $notified_to . $fyi_to);
                     //BOF:mod 20130429
                     /*
                                     //EOF:mod 20130429
                     if (!empty($notified_to)){
                     							$notified_to = '<br/><br/>Action Request marked to: ' . substr($notified_to, 0, -2);
                     }
                     if (!empty($fyi_to)){
                     							$fyi_to = (empty($notified_to) ? '<br/><br/>' : '<br/>') . 'FYI Comment marked to: ' . substr($fyi_to, 0, -2);
                     }
                     if (!empty($emailed_to)){
                     							$emailed_to = (empty($notified_to) && empty($fyi_to) ? '<br/><br/>' : '<br/>') . 'Email sent to: ' . substr($emailed_to, 0, -2);
                     }
                     $this->active_comment->setBody($this->active_comment->getBody() . $notified_to . $fyi_to . $emailed_to);
                     //EOF:mod 20110623
                     $this->active_comment->save();
                                     //BOF:mod 20130429
                     */
                     //EOF:mod 20130429
                     //BOF:mod 20110720 ticketid246
                     /*
                     //EOF:mod 20110720 ticketid246
                     $created_by = $this->active_comment->getCreatedBy();
                     $parent = $active_object;
                     $parent->sendToSubscribers('resources/new_comment', array(
                     			'comment_body' => $this->active_comment->getFormattedBody(),
                     			'comment_url' => $this->active_comment->getViewUrl(),
                     			'created_by_url' => $created_by->getViewUrl(),
                     			'created_by_name' => $created_by->getDisplayName(),
                     			'subscribers_name' => "<br/><br/>-- SET NOTIFICATIONS --<br/>" . $subscribers_name . "<br/><br/>",
                     			'comment_id' => $this->active_comment->getId(),
                     			), $excluded, $parent);
                     //BOF:mod 20110720 ticketid246
                     */
                     //EOF:mod 20110720 ticketid246
                     /*$created_by = $this->active_comment->getCreatedBy();
                     		$variables = array('owner_company_name' => get_owner_company(),
                     				'project_name'       => $this->active_project->getName(),
                     				'project_url'        => $this->active_project->getOverviewUrl(),
                     				'object_type'        => $this->active_comment->getVerboseType(),
                     				'object_name'        => $this->active_comment->getName(),
                     				'comment_body' => $this->active_comment->getFormattedBody(),
                     				'comment_url' => $this->active_comment->getViewUrl(),
                     				'created_by_url' => $created_by->getViewUrl(),
                     				'created_by_name' => $created_by->getDisplayName(),);
                     		ApplicationMailer::send($users, 'resources/new_comment', $variables, $this->active_milestone);*/
                 }
             } elseif (!empty($fyi_users)) {
                 $all_subscribers = $active_object->getSubscribers();
                 foreach ($all_subscribers as $reg_subscriber) {
                     foreach ($fyi_users as $fyi_user_id) {
                         $fyi_user_id = trim($fyi_user_id);
                         if ($reg_subscriber->getId() == $fyi_user_id) {
                             $fyi_to .= $reg_subscriber->getName() . ', ';
                             break;
                         }
                     }
                 }
                 /*$fyi_to = '<br/><br/>FYI Comment marked to: ' . substr($fyi_to, 0, -2);
                 		if (!empty($emailed_to)){
                 			$emailed_to = (empty($fyi_to) ? '<br/><br/>' : '<br/>') . 'Email sent to: ' . substr($emailed_to, 0, -2);
                                  }
                 		$this->active_comment->setBody($this->active_comment->getBody() . $fyi_to . $emailed_to);
                 		$this->active_comment->save();*/
             } elseif (!empty($email_to_user_ids)) {
                 /*$emailed_to = '<br/><br/>Email sent to: ' . substr($emailed_to, 0, -2);
                 		$this->active_comment->setBody($this->active_comment->getBody() . $emailed_to);
                 		$this->active_comment->save();*/
             }
             if (count($email_to_user_ids)) {
                 $users = array();
                 foreach ($email_to_user_ids as $user_id) {
                     if ($user_id != $this->logged_user->getId()) {
                         $users[] = new User($user_id);
                     }
                 }
                 $created_by = $this->active_comment->getCreatedBy();
                 $variables = array('owner_company_name' => get_owner_company(), 'project_name' => $this->active_project->getName(), 'project_url' => $this->active_project->getOverviewUrl(), 'object_type' => $this->active_comment->getVerboseType(), 'object_name' => $this->active_comment->getName(), 'object_body' => $this->active_comment->getFormattedBody(), 'object_url' => $this->active_comment->getViewUrl(), 'comment_body' => $this->active_comment->getFormattedBody(), 'comment_url' => $this->active_comment->getViewUrl(), 'created_by_url' => $created_by->getViewUrl(), 'created_by_name' => $created_by->getDisplayName(), 'details_body' => '', 'comment_id' => $this->active_comment->getId());
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 ApplicationMailer::send($users, 'resources/new_comment', $variables, $this->active_milestone);
                 //BOF:mod 20111101
                 */
                 $parent_id = $this->active_comment->getParentId();
                 $parent_type = $this->active_comment->getParentType();
                 $parent_obj = new $parent_type($parent_id);
                 $attachments = null;
                 $object_attachments = $this->active_comment->getAttachments();
                 if ($object_attachments) {
                     $attachments = array();
                     foreach ($object_attachments as $object_attachment) {
                         $attachments[] = array('path' => $object_attachment->getFilePath(), 'name' => $object_attachment->getName(), 'mime_type' => $object_attachment->getMimeType());
                     }
                 }
                 ApplicationMailer::send($users, 'resources/new_comment', $variables, $parent_obj, $attachments);
                 //EOF:mod 20111101
             }
             //BOF:mod 20121030
             $modify_comments_sorting = false;
             $reply_to_comment_id = $this->request->post('reply_to_comment_id');
             if (!empty($reply_to_comment_id)) {
                 $sql_data = array('integer_field_2' => $reply_to_comment_id);
                 Comments::update($sql_data, "id='" . $this->active_comment->getId() . "'", TABLE_PREFIX . 'project_objects');
                 //$modify_comments_sorting = true;
             }
             //$count = 0;
             /*$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             		mysql_select_db(DB_NAME);
             		$sql = "select * from " . TABLE_PREFIX . "project_objects where parent_id='" . $this->active_comment->getParentId() . "' and parent_type='" . $this->active_comment->getParentType() . "' and type='Comment' and (position is null or position='0')";
             		$result = mysql_query($sql, $link);
             		if (!mysql_num_rows($result) ){
             			$sql = "select max(position) as count from " . TABLE_PREFIX . "project_objects where parent_id='" . $this->active_comment->getParentId() . "' and parent_type='" . $this->active_comment->getParentType() . "' and type='Comment'";
             			$result = mysql_query($sql, $link);
             			$info = mysql_fetch_assoc($result);
             			$count = $info['count'];
             			$sql_data = array('position' => ++$count);
             			Comments::update($sql_data, "id='" . $this->active_comment->getId() . "'", TABLE_PREFIX . 'project_objects');
             		} else {
             			$modify_comments_sorting = true;
             		}
             		mysql_close($link);*/
             //if ($modify_comments_sorting) $this->modify_comments_sorting($count);
             //EOF:mod 20121030
             if ($this->request->isApiCall()) {
                 $this->serveData($this->active_comment, 'comment');
             } else {
                 flash_success('Comment successfully posted');
                 //$this->redirectToUrl($this->active_comment->getRealViewUrl());
                 $this->redirectToUrl($this->active_comment->getParent()->getViewUrl());
             }
             // if
         } else {
             db_rollback();
             if ($this->request->isApiCall()) {
                 $this->serveData($save);
             } else {
                 $this->smarty->assign('errors', $save);
             }
             // if
         }
         // if
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
         }
         // if
     }
     // if
 }
 /**
  * Send email to list of recipients
  * 
  * $to is a list of users who need to receive email notifications. If this 
  * function gets list of email addresses default language will be used. If 
  * we get User instances we'll use language set as prefered on their profile 
  * page
  * 
  * $to can also be a single user or email address
  * 
  * $tpl is a script in format module/name. If / is not present activeCollab 
  * will assume that template is in system module
  * 
  * Context is object that this email is primary related to
  * 
  * $attachments is array of attachments that are structured like this
  *    path -> path to file
  *    name -> name which will be displayed in email (if ommited original filename will be used)
  *    mime_type -> file mime type (if ommited system will determine mime type automatically)
  * here is sample of one $attachments array
  *    $attachments = array(
  *      array('path' => '/work/picture3.png', 'name' => 'simple_file_name.png', 'mime_type' => 'image/png')
  *    );
  * 
  * @param array $to
  * @param string $tpl
  * @param array $replacements
  * @param mixed $context
  * @param array $attachments
  * @return boolean
  */
 function send($to, $tpl, $replacements = null, $context = null, $attachments = null)
 {
     static $mark_as_bulk = null, $empty_return_path = null;
     if (isset($this) && instance_of($this, 'ApplicationMailer')) {
         if (!$this->connected) {
             $this->connect();
         }
         // if
         if (!is_foreachable($to)) {
             if (instance_of($to, 'User') || is_valid_email($to)) {
                 $to = array($to);
             } else {
                 return true;
                 // no recipients
             }
             // if
         }
         // if
         if (strpos($tpl, '/') === false) {
             $template_module = SYSTEM_MODULE;
         } else {
             list($template_module, $template_name) = explode('/', $tpl);
         }
         // if
         $template = EmailTemplates::findById(array('module' => $template_module, 'name' => $template_name));
         if (!instance_of($template, 'EmailTemplate')) {
             return false;
         }
         // if
         $owner_company = get_owner_company();
         if (is_array($replacements)) {
             $replacements['owner_company_name'] = $owner_company->getName();
         } else {
             $replacements = array('owner_company_name' => $owner_company->getName());
         }
         // if
         // Array of messages and recipients organized by language
         $to_send = array();
         // Set default locale (built in one)
         $default_locale = BUILT_IN_LOCALE;
         // Do we have a default language set
         $default_language_id = ConfigOptions::getValue('language');
         if ($default_language_id) {
             $default_language = Languages::findById($default_language_id);
             if (instance_of($default_language, 'Language') && !$default_language->isBuiltIn()) {
                 $default_locale = $default_language->getLocale();
             }
             // if
         }
         // if
         // Cache of loaded languages
         $languages = array();
         // Get from email and from name
         $from_email = ConfigOptions::getValue('notifications_from_email');
         $from_name = ConfigOptions::getValue('notifications_from_name');
         if (!is_valid_email($from_email)) {
             $from_email = ADMIN_EMAIL;
         }
         // if
         if (empty($from_name)) {
             $from_name = $owner_company->getName();
         }
         // if
         // Now prepare messages
         foreach ($to as $recipient) {
             $locale = $default_locale;
             if (instance_of($recipient, 'User')) {
                 $locale = $recipient->getLocale($default_locale);
                 $recipient_name = $recipient->getDisplayName();
                 $recipient_email = $recipient->getEmail();
                 // If same reset name... "name@site.com <*****@*****.**>" can cause
                 // problems with some servers
                 if ($recipient_name == $recipient_email) {
                     $recipient_name = null;
                 }
                 // if
             } else {
                 $recipient_name = null;
                 $recipient_email = $recipient;
             }
             // if
             $language = isset($languages[$locale]) ? $languages[$locale] : Languages::findByLocale($locale);
             // We have message prepared, just need to add a recipient
             //BOF:mod
             //if(isset($to_send[$locale])) {
             if (isset($to_send[$locale]) && $tpl != 'resources/new_comment') {
                 //EOF:moid
                 $to_send[$locale]['recipients']->add($recipient_email, $recipient_name);
                 // Need to prepare message and add first recipient
             } else {
                 //BOF:mod 20110711 ticketid231
                 if ($tpl == 'resources/new_comment') {
                     $mark_actionrequest_complete = '';
                     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                     mysql_select_db(DB_NAME);
                     $query = "select a.is_action_request, b.project_id from healingcrystals_assignments_action_request a inner join healingcrystals_project_objects b on a.comment_id=b.id where a.comment_id='" . $replacements['comment_id'] . "' and a.user_id='" . $recipient->getId() . "'";
                     $result = mysql_query($query);
                     if (mysql_num_rows($result)) {
                         $info = mysql_fetch_assoc($result);
                         if ($info['is_action_request'] == '1') {
                             $mark_actionrequest_complete = '<div style="margin:5px 0 5px 0;"><a href="' . assemble_url('project_comment_action_request_completed', array('project_id' => $info['project_id'], 'comment_id' => $replacements['comment_id'])) . '">Click here to Mark this Action Request Complete</a></div>';
                         }
                     }
                     mysql_close($link);
                     $replacements['mark_actionrequest_complete'] = $mark_actionrequest_complete;
                 }
                 //EOF:mod 20110711 ticketid231
                 $subject = $template->getSubject($locale);
                 $body = $template->getBody($locale);
                 foreach ($replacements as $k => $v) {
                     if (is_array($v)) {
                         $v = isset($v[$locale]) ? $v[$locale] : array_shift($v);
                     }
                     // if
                     $subject = str_replace(":{$k}", $v, $subject);
                     if (str_ends_with($k, '_body')) {
                         $body = str_replace(":{$k}", $v, $body);
                     } else {
                         //$body = str_replace(":$k", clean($v), $body);
                         $body = str_replace(":{$k}", $v, $body);
                     }
                     // if
                 }
                 // foreach
                 //BOF:mod
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 if ($tpl=='resources/new_comment'){
                 	$add_to_subject = '';
                 	            $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 				mysql_select_db(DB_NAME);
                 				$query = "select a.is_action_request, a.is_fyi, a.priority_actionrequest, b.project_id from healingcrystals_assignments_action_request a inner join healingcrystals_project_objects b on a.comment_id=b.id where a.comment_id='" . $replacements['comment_id'] . "' and a.user_id='" . $recipient->getId() . "'";
                 				$result = mysql_query($query, $link);
                 				if (mysql_num_rows($result)){
                 					$info = mysql_fetch_assoc($result);
                 					$flag_action_request = $info['is_action_request'];
                 					$flag_fyi = $info['is_fyi'];
                 					$priority = $info['priority_actionrequest'];
                 					if ($flag_action_request=='1'){
                 						switch($priority){
                 							case PRIORITY_LOWEST:
                 								$priority_desc = 'Lowest Priority ';
                 								break;
                 							case PRIORITY_LOW:
                 								$priority_desc = 'Low Priority ';
                 								break;
                 							case PRIORITY_NORMAL:
                 								$priority_desc = 'Normal Priority ';
                 								break;
                 							case PRIORITY_HIGH:
                 								$priority_desc = 'High Priority ';
                 								break;
                 							case PRIORITY_HIGHEST:
                 								$priority_desc = 'Highest Priority ';
                 								break;
                 							default:
                 								$priority_desc = '';
                 						}
                 						$add_to_subject .= $priority_desc . 'Action Request';
                 						
                 					}
                 					if ($flag_fyi=='1'){
                 						if (!empty($add_to_subject)){
                 							$add_to_subject .= '/';
                 						}
                 						$add_to_subject .= 'FYI';
                 						$body = '<a href="' . assemble_url('project_comment_fyi_read', array('project_id' => $info['project_id'], 'comment_id' => $replacements['comment_id'])) . '">Mark this FYI Notification as Read</a>' . "<br>\n" . $body;
                 					}
                 					if (!empty($add_to_subject)){
                 						$add_to_subject .= ' - ';
                 					}
                 				}
                 				mysql_close($link);
                 	            $subject =  $add_to_subject . $subject;
                 }
                 //EOF:mod
                 //BOF:mod 20111101
                 */
                 //EOF:mod 20111101
                 //BOF:mod 20111110 #493
                 if ($tpl == 'resources/new_comment') {
                     $subject .= ' [CID' . $replacements['comment_id'] . ']';
                 }
                 //EOF:mod 20111110 #493
                 event_trigger('on_prepare_email', array($tpl, $recipient_email, $context, &$body, &$subject, &$attachments, &$language, $replacements['subscribers_name']));
                 // if files need to be attached, message will be multipart
                 if (is_foreachable($attachments)) {
                     $message = new Swift_Message($subject);
                     $message->attach(new Swift_Message_Part($body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET));
                     foreach ($attachments as $attachment) {
                         $file_path = array_var($attachment, 'path', null);
                         if (file_exists($file_path)) {
                             $message->attach(new Swift_Message_Attachment(new Swift_File($file_path), array_var($attachment, 'name', basename($file_path)), array_var($attachment, 'mime_type', mime_content_type($file_path))));
                         }
                     }
                     // if
                 } else {
                     $message = new Swift_Message($subject, $body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET);
                 }
                 // if
                 // Load values...
                 if ($mark_as_bulk === null || $empty_return_path === null) {
                     $mark_as_bulk = (bool) ConfigOptions::getValue('mailing_mark_as_bulk');
                     $empty_return_path = (bool) ConfigOptions::getValue('mailing_empty_return_path');
                 }
                 // if
                 // Custom headers (to prevent auto responders)
                 if ($mark_as_bulk) {
                     $message->headers->set('Auto-Submitted', 'auto-generated');
                     $message->headers->set('Precedence', 'bulk');
                 }
                 // if
                 if ($empty_return_path) {
                     $message->headers->set('Return-Path', '<>');
                 } else {
                     $message->headers->set('Return-Path', "<{$from_email}>");
                 }
                 // if
                 if (!isset($to_send[$locale])) {
                     $to_send[$locale] = array('recipients' => new Swift_RecipientList(), 'message' => $message);
                 }
                 //BOF:mod
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 if ($tpl=='resources/new_comment'){
                     $to_send[$locale]['modified_subject'][$recipient_email] =  $subject;
                 }
                 //BOF:mod 20111101
                 */
                 //EOF:mod 20111101
                 //EOF:mod
                 $to_send[$locale]['recipients']->add($recipient_email, $recipient_name);
             }
             // if
         }
         // foreach
         if (is_foreachable($to_send)) {
             foreach ($to_send as $locale => $message_data) {
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 $this->swift->batchSend($message_data['message'], $message_data['recipients'], new Swift_Address($from_email, $from_name), $message_data['modified_subject']);
                 //BOF:mod 20111101
                 */
                 $this->swift->batchSend($message_data['message'], $message_data['recipients'], new Swift_Address($from_email, $from_name));
                 //EOF:mod 20111101
             }
             // foreach
         }
         // if
         return true;
     } else {
         $instance =& ApplicationMailer::instance();
         return $instance->send($to, $tpl, $replacements, $context, $attachments);
     }
     // if
 }
 function register_assignees_flag($assignees_flag = array(), $is_new_object = false)
 {
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     mysql_select_db(DB_NAME);
     if (!$is_new_object) {
         $query = "delete from healingcrystals_assignments_flag_fyi_actionrequest where object_id='" . $this->getId() . "'";
         mysql_query($query, $link);
     }
     $users = array();
     foreach ($assignees_flag['flag_fyi'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_fyi'] = '1';
     }
     foreach ($assignees_flag['flag_actionrequest'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_actionrequest'] = '1';
     }
     foreach ($assignees_flag['priority_actionrequest'] as $entry) {
         $vals = explode('_', $entry);
         list($temp_user_id, $priority) = $vals;
         if (array_key_exists((string) $temp_user_id, $users) && $users[(string) $temp_user_id]['flag_actionrequest'] == '1') {
             $users[(string) $temp_user_id]['priority_actionrequest'] = $priority;
         }
     }
     foreach ($assignees_flag['flag_email'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_email'] = '1';
     }
     foreach ($users as $user_id => $flags) {
         $query = "insert into healingcrystals_assignments_flag_fyi_actionrequest (user_id, object_id, flag_fyi, flag_actionrequest, priority_actionrequest, email_flag) values ('" . $user_id . "', '" . $this->getId() . "', '" . $flags['flag_fyi'] . "', '" . $flags['flag_actionrequest'] . "', '" . $flags['priority_actionrequest'] . "', '" . $flags['flag_email'] . "')";
         //mysql_query("insert into testing (date_added, content)  values (now(), '" . mysql_real_escape_string($query) . "')");
         mysql_query($query, $link);
     }
     //BOF:mod 20111011 #449
     if ($is_new_object) {
         $query = "select user_id from healingcrystals_assignments_flag_fyi_actionrequest where object_id='" . $this->getId() . "' and email_flag='1'";
         $result = mysql_query($query);
         $email_to = array();
         if (mysql_num_rows($result)) {
             while ($entry = mysql_fetch_assoc($result)) {
                 $email_to[] = new User($entry['user_id']);
             }
         }
         if (count($email_to)) {
             $owner_company = get_owner_company();
             $project = $this->getProject();
             // Prepare object type translations
             if (is_foreachable($languages)) {
                 $object_type = array();
                 foreach ($languages as $language) {
                     $object_type[$language->getLocale()] = $this->getVerboseType(false, $language);
                 }
                 // foreach
             } else {
                 $object_type = $this->getVerboseType();
             }
             // if
             $created_by_id = $this->getCreatedById();
             $created_by = new User($created_by_id);
             $variables = array('details_body' => EmailTemplates::renderProjectObjectDetails($this, $languages), 'project_name' => $project->getName(), 'project_url' => $project->getOverviewUrl(), 'object_type' => $object_type, 'object_name' => $this->getName(), 'object_body' => $this->getFormattedBody(), 'object_url' => $this->getViewUrl(), 'owner_company_name' => $owner_company->getName(), 'created_by_name' => $created_by->getDisplayName(), 'created_by_url' => $created_by->getViewUrl());
             if ($context === null) {
                 $context = $this->getNotificationContext();
             }
             // if
             ApplicationMailer::send($email_to, 'resources/task_assigned', $variables, $context);
         }
     }
     //EOF:mod 20111011 #449
     mysql_close($link);
 }
 /**
  * Upload file document page action
  * 
  * @param void
  * @return void
  */
 function upload_file()
 {
     $this->wireframe->print_button = false;
     if (!Document::canAdd($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $file = $_FILES['file'];
     $file_data = $this->request->post('file');
     if (!is_array($file_data)) {
         $file_data = array('category_id' => $this->active_document_category->getId());
     }
     // if
     require_once SMARTY_PATH . '/plugins/modifier.filesize.php';
     $this->smarty->assign(array('file_data' => $file_data, 'max_upload_size' => smarty_modifier_filesize(get_max_upload_size())));
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $this->active_document->setAttributes($file_data);
         if (is_array($file)) {
             $destination_file = get_available_uploads_filename();
             if (move_uploaded_file($file['tmp_name'], $destination_file)) {
                 if (FIX_UPLOAD_PERMISSION !== false) {
                     @chmod($destination_file, FIX_UPLOAD_PERMISSION);
                 }
                 // if
                 $this->active_document->setName($file['name']);
                 $this->active_document->setBody(basename($destination_file));
                 $this->active_document->setMimeType($file['type']);
             }
             // if
         }
         // if
         $this->active_document->setCreatedBy($this->logged_user);
         $this->active_document->setType('file');
         $save = $this->active_document->save();
         if ($save && !is_error($save)) {
             $notify_user_ids = $this->request->post('notify_users');
             if (is_foreachable($notify_user_ids)) {
                 $notify_users = Users::findByIds($notify_user_ids);
                 $owner_company = get_owner_company();
                 if (is_foreachable($notify_users)) {
                     ApplicationMailer::send($notify_users, 'documents/new_upload_file_document', array('document_name' => $this->active_document->getName(), 'created_by_name' => $this->active_document->getCreatedByName(), 'created_by_url' => $this->logged_user->getViewUrl(), 'document_url' => $this->active_document->getViewUrl(), 'owner_company_name' => $owner_company->getName()), $this->active_document);
                 }
                 // if
             }
             // if
             db_commit();
             flash_success('Document ":document_name" has been uploaded', array('document_name' => $this->active_document->getName()));
             $this->redirectTo('documents');
         } else {
             db_rollback();
             $this->smarty->assign('errors', $save);
         }
         // if
     }
     // if
 }
 function importPendingEmailAsComment(&$incoming_mail, &$project, &$user, &$mailbox, $page_id = '')
 {
     $parent = ProjectObjects::findById(!empty($page_id) ? $page_id : $incoming_mail->getParentId());
     //EOF:mod 20120820
     if (!instance_of($parent, 'ProjectObject')) {
         // parent object does not exists
         $incoming_mail->setState(INCOMING_MAIL_STATUS_PARENT_NOT_EXISTS);
         $incoming_mail_save = $incoming_mail->save();
         return new Error(incoming_mail_module_get_status_description(INCOMING_MAIL_STATUS_PARENT_NOT_EXISTS));
     }
     // if
     if (!$mailbox->getAcceptAllRegistered() && instance_of($user, 'User') && !$parent->canComment($user)) {
         // user cannot create comments to parent object
         $incoming_mail->setState(INCOMING_MAIL_STATUS_USER_CANNOT_CREATE_COMMENT);
         $incoming_mail_save = $incoming_mail->save();
         return new Error(incoming_mail_module_get_status_description(INCOMING_MAIL_STATUS_USER_CANNOT_CREATE_COMMENT));
     } else {
         if (!$parent->can_have_comments || $parent->getIsLocked() || $parent->getState() < STATE_VISIBLE) {
             // parent object can't have comments
             $incoming_mail->setState(INCOMING_MAIL_STATUS_USER_CANNOT_CREATE_COMMENT);
             $incoming_mail_save = $incoming_mail->save();
             return new Error(incoming_mail_module_get_status_description(INCOMING_MAIL_STATUS_USER_CANNOT_CREATE_COMMENT));
         }
         // if
     }
     // if
     $comment = new Comment();
     $comment->log_activities = false;
     $comment->setCreatedBy($user);
     $comment->setCreatedOn($incoming_mail->getCreatedOn());
     $comment->setProjectId($parent->getProjectId());
     $comment->setState(STATE_VISIBLE);
     $comment->setSource(OBJECT_SOURCE_EMAIL);
     $comment->setVisibility($parent->getVisibility());
     $comment->setParent($parent);
     $body_content = '';
     if (stripos($incoming_mail->getBody(), '-- REPLY ABOVE THIS LINE --') !== false) {
         $body_content = substr($incoming_mail->getBody(), 0, strpos($incoming_mail->getBody(), '-- REPLY ABOVE THIS LINE --'));
     } else {
         $body_content = $incoming_mail->getBody();
     }
     $comment->setBody($body_content);
     IncomingMailImporter::attachFilesToProjectObject($incoming_mail, $comment);
     //$save = $comment->save();
     $save = $comment->save(true);
     if ($save && !is_error($save)) {
         $activity = new NewCommentActivityLog();
         $activity->log($comment, $user);
         if (instance_of($user, 'User')) {
             $parent->subscribe($user);
         }
         // if
         $comment->ready();
         //BOF:mod 20111110 #493
         preg_match("/\\[CID(.*?)\\](.*)/is", $incoming_mail->getSubject(), $results);
         if (count($results) > 0) {
             $project = new Project($parent->getProjectId());
             $variables = array('owner_company_name' => get_owner_company(), 'project_name' => $project->getName(), 'project_url' => $project->getOverviewUrl(), 'object_type' => $comment->getVerboseType(), 'object_name' => $comment->getName(), 'object_body' => $comment->getFormattedBody(), 'object_url' => $comment->getViewUrl(), 'comment_body' => $comment->getFormattedBody(), 'comment_url' => $comment->getViewUrl(), 'created_by_url' => $user->getViewUrl(), 'created_by_name' => $user->getDisplayName(), 'details_body' => '', 'comment_id' => $comment->getId());
             $emailed_comment_id = $results[1];
             $emailed_comment = new Comment($emailed_comment_id);
             $emailed_comment_creator_id = $emailed_comment->getCreatedById();
             $email_to = array();
             $temp_user_id = $user->getId();
             $temp_comment_id = $comment->getId();
             $rows = db_execute_all("select user_id from " . TABLE_PREFIX . "assignments_action_request where comment_id='" . $emailed_comment_id . "' and marked_for_email='1'");
             foreach ($rows as $row) {
                 if ($row['user_id'] != $temp_user_id) {
                     $email_to[] = new User($row['user_id']);
                     db_execute("insert into " . TABLE_PREFIX . "assignments_action_request (user_id, marked_for_email, selected_by_user_id, comment_id, date_added) values ('" . $row['user_id'] . "', '1', '" . $temp_user_id . "', '" . $temp_comment_id . "', now())");
                 }
             }
             $row = db_execute_one("select a.selected_by_user_id from " . TABLE_PREFIX . "assignments_action_request a where a.comment_id='" . $emailed_comment_id . "' and a.marked_for_email='1' and a.selected_by_user_id not in (select b.user_id from " . TABLE_PREFIX . "assignments_action_request b where b.comment_id='" . $emailed_comment_id . "' and b.marked_for_email='1') limit 0, 1");
             if (!empty($row['selected_by_user_id'])) {
                 if ($row['selected_by_user_id'] != $temp_user_id) {
                     $email_to[] = new User($row['selected_by_user_id']);
                     db_execute("insert into " . TABLE_PREFIX . "assignments_action_request (user_id, marked_for_email, selected_by_user_id, comment_id, date_added) values ('" . $row['selected_by_user_id'] . "', '1', '" . $temp_user_id . "', '" . $temp_comment_id . "', now())");
                 }
             }
             //ApplicationMailer::send(array(new User($emailed_comment_creator_id)), 'resources/new_comment', $variables, $parent);
             $attachments = null;
             $object_attachments = $comment->getAttachments();
             if ($object_attachments) {
                 $attachments = array();
                 foreach ($object_attachments as $object_attachment) {
                     $attachments[] = array('path' => $object_attachment->getFilePath(), 'name' => $object_attachment->getName(), 'mime_type' => $object_attachment->getMimeType());
                 }
             }
             ApplicationMailer::send($email_to, 'resources/new_comment', $variables, $parent, $attachments);
         }
         //EOF:mod 20111110 #493
         if (!empty($page_id)) {
             //$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             //mysql_select_db(DB_NAME, $link);
             //mysql_query("insert into testing (date_added, content) values (now(), 'Page_id: " . $page_id . "')");
             //mysql_close($link);
             $task =& IncomingMailImporter::importPendingEmailToTaskList($incoming_mail, $project, $user, $page_id, $comment);
             return $task;
         } else {
             return $comment;
         }
     }
     // if
     return $save;
 }