/**
  * Show invoicing settings panel
  *
  * @param void
  * @return null
  */
 function index()
 {
     require_once INVOICING_MODULE_PATH . '/models/InvoicePdfGenerator.class.php';
     $paper_formats = array(PAPER_FORMAT_A4, PAPER_FORMAT_A3, PAPER_FORMAT_A5, PAPER_FORMAT_LETTER, PAPER_FORMAT_LEGAL);
     $paper_orientations = array(PAPER_ORIENTATION_PORTRAIT, PAPER_ORIENTATION_LANDSCAPE);
     $pdf_settings_data = $this->request->post('pdf_settings');
     if (!is_array($pdf_settings_data)) {
         $pdf_settings_data = array('paper_format' => ConfigOptions::getValue('invoicing_pdf_paper_format'), 'paper_orientation' => ConfigOptions::getValue('invoicing_pdf_paper_orientation'), 'header_text_color' => ConfigOptions::getValue('invoicing_pdf_header_text_color'), 'page_text_color' => ConfigOptions::getValue('invoicing_pdf_page_text_color'), 'border_color' => ConfigOptions::getValue('invoicing_pdf_border_color'), 'background_color' => ConfigOptions::getValue('invoicing_pdf_background_color'));
     }
     // if
     if ($this->request->isSubmitted()) {
         db_begin_work();
         ConfigOptions::setValue('invoicing_pdf_paper_format', array_var($pdf_settings_data, 'paper_format', 'A4'));
         ConfigOptions::setValue('invoicing_pdf_paper_orientation', array_var($pdf_settings_data, 'paper_orientation', 'Portrait'));
         ConfigOptions::setValue('invoicing_pdf_header_text_color', array_var($pdf_settings_data, 'header_text_color', '000000'));
         ConfigOptions::setValue('invoicing_pdf_page_text_color', array_var($pdf_settings_data, 'page_text_color', '000000'));
         ConfigOptions::setValue('invoicing_pdf_border_color', array_var($pdf_settings_data, 'border_color', '000000'));
         ConfigOptions::setValue('invoicing_pdf_background_color', array_var($pdf_settings_data, 'background_color', 'FFFFFF'));
         db_commit();
         flash_success('Successfully modified PDF settings');
         $this->redirectTo('admin_invoicing_pdf');
     }
     // if
     $this->smarty->assign(array('paper_formats' => $paper_formats, 'paper_orientations' => $paper_orientations, 'pdf_settings_data' => $pdf_settings_data));
 }
 /**
  * Delete all items for a invoice
  *
  * @param Invoice $invoice
  * @return null
  */
 function deleteByInvoice($invoice)
 {
     db_begin_work();
     $execute = db_execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ?', $invoice->getId());
     if ($execute && !is_error($execute)) {
         $delete = InvoiceItems::delete(array('invoice_id = ?', $invoice->getId()));
         if ($delete && !is_error($delete)) {
             db_commit();
         } else {
             db_rollback();
         }
         // if
         return $delete;
     } else {
         db_rollback();
         return $execute;
     }
     // if
 }
 /**
  * Set $currency as default
  *
  * @param Currency $currency
  * @return boolean
  */
 function setDefault($currency)
 {
     if ($currency->getIsDefault()) {
         return true;
     }
     // if
     db_begin_work();
     $currency->setIsDefault(true);
     $update = $currency->save();
     if ($update && !is_error($update)) {
         $update = db_execute('UPDATE ' . TABLE_PREFIX . 'currencies SET is_default = ? WHERE id != ?', false, $currency->getId());
         cache_remove_by_pattern(TABLE_PREFIX . 'currencies_id_*');
         if ($update && !is_error($update)) {
             db_commit();
             return true;
         }
         // if
     }
     // if
     db_rollback();
     return $update;
 }
 /**
  * Set ID-s of related time records
  *
  * @param array $ids
  * @return boolean
  */
 function setTimeRecordIds($ids)
 {
     db_begin_work();
     $execute = db_execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ? && item_id = ?', $this->getInvoiceId(), $this->getId());
     if ($execute && !is_error($execute)) {
         if (is_foreachable($ids)) {
             $to_insert = array();
             $invoice_id = $this->getInvoiceId();
             $item_id = $this->getId();
             foreach ($ids as $id) {
                 $id = (int) $id;
                 if ($id && !isset($to_insert[$id])) {
                     $to_insert[$id] = "({$invoice_id}, {$item_id}, {$id})";
                 }
                 // if
             }
             // foreach
             if (is_foreachable($to_insert)) {
                 $execute = db_execute('INSERT INTO ' . TABLE_PREFIX . 'invoice_time_records (invoice_id, item_id, time_record_id) VALUES ' . implode(', ', $to_insert));
                 if (!$execute || is_error($execute)) {
                     db_rollback();
                     return $execute;
                 }
                 // if
             }
             // if
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $execute;
     }
     // if
 }
 /**
  * Upload single file
  *
  * @param void
  * @return null
  */
 function upload_single()
 {
     if ($this->request->isSubmitted()) {
         if (!File::canAdd($this->logged_user, $this->active_project)) {
             if ($this->request->isApiCall()) {
                 $this->httpError(HTTP_ERR_FORBIDDEN, null, true, true);
             } else {
                 die('error - upload not permitted');
             }
             // if
         }
         // if
         $file_data = $this->request->post('file');
         if (!is_array($file_data)) {
             $file_data = array('milestone_id' => $this->request->get('milestone_id'), 'visibility' => $this->active_project->getDefaultVisibility());
             if (instance_of($this->active_category, 'Category')) {
                 $file_data['parent_id'] = $this->active_category->getId();
             }
             // if
         }
         // if
         $this->smarty->assign('file_data', $file_data);
         if ($this->request->isSubmitted()) {
             db_begin_work();
             $this->active_file = new File();
             $attached = attach_from_files($this->active_file, $this->logged_user);
             // Do we have an upload error?
             if (is_error($attached) || $attached != 1) {
                 if ($this->request->isApiCall()) {
                     $this->serveData(is_error($attached) ? $attached : new Error('0 files uploaded'));
                 } else {
                     die('error - nothing uploaded');
                 }
                 // if
             }
             // if
             $this->active_file->setAttributes($file_data);
             if ($this->active_file->getName() == '') {
                 $this->active_file->setName($this->active_file->pending_files[0]['name']);
             }
             // if
             $this->active_file->setRevision(1);
             $this->active_file->setProjectId($this->active_project->getId());
             if (trim($this->active_file->getCreatedByName()) == '' || trim($this->active_file->getCreatedByEmail()) == '') {
                 $this->active_file->setCreatedBy($this->logged_user);
             }
             // if
             $this->active_file->setState(STATE_VISIBLE);
             $save = $this->active_file->save();
             if ($save && !is_error($save)) {
                 if ($this->active_file->countRevisions() > 0) {
                     $subscribers = array($this->logged_user->getId());
                     if (is_foreachable($this->request->post('notify_users'))) {
                         $subscribers = array_merge($subscribers, $this->request->post('notify_users'));
                     } else {
                         $subscribers[] = $this->active_project->getLeaderId();
                     }
                     // if
                     if (!in_array($this->active_project->getLeaderId(), $subscribers)) {
                         $subscribers[] = $this->active_project->getLeaderId();
                     }
                     // if
                     Subscriptions::subscribeUsers($subscribers, $this->active_file);
                     db_commit();
                     $this->active_file->ready();
                     if ($this->request->isApiCall()) {
                         $this->serveData($this->active_file, 'file');
                     } else {
                         die('success');
                         // async
                     }
                     // if
                 } else {
                     if ($this->request->isApiCall()) {
                         $this->httpError(HTTP_ERR_OPERATION_FAILED, null, true, true);
                     } else {
                         die('error - unable to attach file');
                     }
                     // if
                 }
                 // if
             } else {
                 if ($this->request->isApiCall()) {
                     $this->serveData($save);
                 } else {
                     die('error - could not save file object');
                     // async
                 }
                 // if
             }
             // if
         }
         // if
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
         } else {
             die('error - request is not POST request');
             // async
         }
         // if
     }
     // if
 }
 /**
  * Delete document category
  *
  * @param void
  * @return void
  */
 function delete()
 {
     if ($this->active_document_category->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_document_category->canDelete($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $delete = $this->active_document_category->delete();
         if ($delete && !is_error($delete)) {
             db_commit();
             if ($this->request->isApiCall()) {
                 $this->httpOk();
             } else {
                 flash_success('Document category ":name" has been deleted', array('name' => $this->active_document_category->getName()));
                 $this->redirectTo('document_categories');
             }
             // if
         } else {
             db_rollback();
             if ($this->request->isAsyncCall()) {
                 $this->serveData($delete);
             } else {
                 flash_success('Failed to delete ":name" document category', array('name' => $this->active_document_category->getName()));
                 $this->redirectTo('document_categories');
             }
             // if
         }
         // if
     } else {
         $this->httpError(HTTP_ERR_BAD_REQUEST);
     }
     // if
 }
 /**
  * Add people to the project
  *
  * @param void
  * @return null
  */
 function add_people()
 {
     if (!$this->active_project->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $project_users = $this->active_project->getUsers();
     if (is_foreachable($project_users)) {
         $exclude_users = objects_array_extract($project_users, 'getId');
     } else {
         $exclude_users = null;
     }
     // if
     $this->smarty->assign(array('exclude_users' => $exclude_users));
     if ($this->request->isSubmitted()) {
         $user_ids = $this->request->post('users');
         if (!is_foreachable($user_ids)) {
             flash_error('No users selected');
             $this->redirectToUrl($this->active_project->getViewUrl());
         }
         // if
         $users = Users::findByIds($user_ids);
         $project_permissions = $this->request->post('project_permissions');
         $role = null;
         $role_id = (int) array_var($project_permissions, 'role_id');
         if ($role_id) {
             $role = Roles::findById($role_id);
         }
         // if
         if (instance_of($role, 'Role') && $role->getType() == ROLE_TYPE_PROJECT) {
             $permissions = null;
         } else {
             $permissions = array_var($project_permissions, 'permissions');
             if (!is_array($permissions)) {
                 $permissions = null;
             }
             // if
         }
         // if
         if (is_foreachable($users)) {
             db_begin_work();
             $added = array();
             foreach ($users as $user) {
                 $add = $this->active_project->addUser($user, $role, $permissions);
                 if ($add && !is_error($add)) {
                     $added[] = $user->getDisplayName();
                 } else {
                     db_rollback();
                     flash_error('Failed to add ":user" to ":project" project', array('user' => $user->getDisplayName(), 'project' => $this->active_project->getName()));
                     $this->redirectToUrl($this->active_project->getAddPeopleUrl());
                 }
                 // if
             }
             // foreach
             db_commit();
             if ($this->request->isApiCall()) {
                 $this->httpOk();
             } else {
                 require_once SMARTY_PATH . '/plugins/function.join.php';
                 flash_success(':users added to :project project', array('users' => smarty_function_join(array('items' => $added)), 'project' => $this->active_project->getName()));
                 $this->redirectToUrl($this->active_project->getPeopleUrl());
             }
             // if
         }
         // if
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST);
         }
         // if
     }
     // if
 }
 /**
  * Update field properties for child objects by parent
  * 
  * $properties is an array where key is setter name and value is new value
  *
  * @param ProjectObject $parent
  * @param array $properties
  * @param array $types
  * @return boolean
  */
 function updatePropertiesByParent($parent, $properties, $types)
 {
     if (is_foreachable($properties) && is_foreachable($types)) {
         $objects = ProjectObjects::findBySQL('SELECT * FROM ' . TABLE_PREFIX . 'project_objects WHERE parent_id = ? AND type IN (?)', array($parent->getId(), $types));
         if (is_foreachable($objects)) {
             db_begin_work();
             foreach ($objects as $object) {
                 foreach ($properties as $setter => $value) {
                     $object->{$setter}($value);
                 }
                 // if
                 $object->save();
             }
             // foreach
             db_commit();
         }
         // if
     }
     // if
     return true;
 }
 /**
  * Reschedule selected milestone
  *
  * @param void
  * @return null
  */
 function reschedule()
 {
     if ($this->active_milestone->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_milestone->canEdit($this->logged_user)) {
         $this->httpError($this->logged_user);
     }
     // if
     $milestone_data = $this->request->post('milestone');
     if (!is_array($milestone_data)) {
         $milestone_data = array('start_on' => $this->active_milestone->getStartOn(), 'due_on' => $this->active_milestone->getDueOn(), 'reschedule_milstone_objects' => false);
     }
     // if
     $this->smarty->assign('milestone_data', $milestone_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $old_due_on = new DateValue($this->active_milestone->getDueOn());
         $new_start_on = new DateValue(array_var($milestone_data, 'start_on'));
         $new_due_on = new DateValue(array_var($milestone_data, 'due_on'));
         $reschedule_tasks = (bool) array_var($milestone_data, 'reschedule_milstone_objects');
         $successive_milestones = Milestones::findSuccessiveByMilestone($this->active_milestone, STATE_VISIBLE, $this->logged_user->getVisibility());
         // before we update timestamp
         $reschedule = $this->active_milestone->reschedule($new_start_on, $new_due_on, $reschedule_tasks);
         if ($reschedule && !is_error($reschedule)) {
             //if (instance_of($new_due_on, 'DateValue')){
             if ($new_due_on->getTimestamp() != $old_due_on->getTimestamp()) {
                 $with_successive = array_var($milestone_data, 'with_sucessive');
                 $to_move = null;
                 switch (array_var($with_successive, 'action')) {
                     case 'move_all':
                         $to_move = $successive_milestones;
                         break;
                     case 'move_selected':
                         $selected_milestones = array_var($with_successive, 'milestones');
                         if (is_foreachable($selected_milestones)) {
                             $to_move = Milestones::findByIds($selected_milestones, STATE_VISIBLE, $this->logged_user->getVisibility());
                         }
                         // if
                         break;
                 }
                 // switch
                 if (is_foreachable($to_move)) {
                     $diff = $new_due_on->getTimestamp() - $old_due_on->getTimestamp();
                     foreach ($to_move as $to_move_milestone) {
                         $milestone_start_on = $to_move_milestone->getStartOn();
                         $milestone_due_on = $to_move_milestone->getDueOn();
                         $new_milestone_start_on = $milestone_start_on->advance($diff, false);
                         $new_milestone_due_on = $milestone_due_on->advance($diff, false);
                         $to_move_milestone->reschedule($new_milestone_start_on, $new_milestone_due_on, $reschedule_tasks);
                     }
                     // foreach
                 }
                 // if
             }
             // if
             db_commit();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 //flash_success('Milestone ":name" has been updated', array('name' => $this->active_milestone->getName()), false, true);
                 flash_success('Project ":name" has been updated', array('name' => $this->active_milestone->getName()), false, true);
                 $this->redirectToUrl($this->active_milestone->getViewUrl());
             } else {
                 $this->serveData($this->active_milestone);
             }
             // if
             //}
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 $this->smarty->assign('errors', $reschedule);
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
 /**
  * Edit repository
  *
  * @param null
  * @return void
  */
 function edit()
 {
     if (!$this->active_repository->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $repository_data = $this->request->post('repository');
     if (!is_array($repository_data)) {
         $repository_data = array('name' => $this->active_repository->getName(), 'url' => $this->active_repository->getUrl(), 'username' => $this->active_repository->getUsername(), 'password' => $this->active_repository->getPassword(), 'repositorytype' => $this->active_repository->getRepositoryType(), 'updatetype' => $this->active_repository->getUpdateType(), 'visibility' => $this->active_repository->getVisibility());
     }
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $this->active_repository->setAttributes($repository_data);
         $this->active_repository->loadEngine($this->active_repository->getRepositoryType());
         $this->repository_engine = new RepositoryEngine($this->active_repository);
         $this->repository_engine->triggerred_by_handler = true;
         $result = $this->repository_engine->testRepositoryConnection();
         if ($result === true) {
             $save = $this->active_repository->save();
             if ($save && !is_error($save)) {
                 db_commit();
                 flash_success(lang('Repository has been successfully updated'));
                 $this->redirectToUrl($this->active_repository->getHistoryUrl());
             } else {
                 db_rollback();
                 $this->smarty->assign('errors', $save);
             }
             //if
         } else {
             db_rollback();
             $errors = new ValidationErrors();
             $errors->addError(lang('Failed to connect to repository: :message', array('message' => $result)));
             $this->smarty->assign('errors', $errors);
         }
         // if
     }
     // if
     js_assign('repository_test_connection_url', assemble_url('repository_test_connection', array('project_id' => $this->active_project->getId())));
     $this->smarty->assign(array('types' => $this->active_repository->types, 'update_types' => $this->active_repository->update_types, 'repository_data' => $repository_data, 'active_repository' => $this->active_repository, 'disable_url_and_type' => instance_of($this->active_repository->getLastCommit(), 'Commit'), 'aid_url' => lang('The path to the existing repository cannot be changed'), 'aid_engine' => lang('Repository type cannot be changed')));
 }
 /**
  * Cleanup after delete
  * 
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete_config_options = UserConfigOptions::deleteByOption('default_assignments_filter');
     if (!$delete_config_options || is_error($delete_config_options)) {
         db_rollback();
         return $delete_config_options;
     }
     // if
     $delete = parent::delete();
     if (!$delete || is_error($delete)) {
         db_rollback();
         return $delete;
     }
     // if
     db_commit();
     return true;
 }
 /**
  * Call object function and server result to client
  * 
  * Most of the actions in this controller look the same. This simple 
  * implementation holds behavior that is same for almost all the actions. 
  * Copying is bad :)
  * 
  * $success_message and $error_message are language patters. Variables that 
  * are provided by this functions to the patterns are:
  * 
  * - name - object name
  * - type - object ype
  *
  * @param string $method
  * @param array $params
  * @param string $success_message
  * @param string $error_message
  * @return null
  */
 function executeOnActiveObject($method, $params = null, $success_message = '', $error_message = '')
 {
     if (empty($method) || empty($success_message) || empty($error_message)) {
         $this->httpError(HTTP_ERR_BAD_REQUEST);
     }
     // if
     if ($this->request->isSubmitted()) {
         db_begin_work();
         if (is_array($params)) {
             $action = call_user_func_array(array(&$this->active_object, $method), $params);
         } else {
             $action = call_user_func(array(&$this->active_object, $method));
         }
         // if
         if ($action && !is_error($action)) {
             db_commit();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 if ($this->request->get('async')) {
                     $this->httpOk();
                 }
                 // if
                 flash_success($success_message, null, true);
                 $this->redirectToReferer($this->active_object->getViewUrl());
             } else {
                 $this->serveData($this->active_object, strtolower($this->active_object->getType()));
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_error($error_message, null, true);
                 $this->redirectToReferer($this->active_object->getViewUrl());
             } else {
                 $this->httpError(HTTP_ERR_OPERATION_FAILED, null, true, $this->request->isApiCall());
             }
             // if
         }
         // if
     } else {
         $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, $this->request->isApiCall());
     }
     // if
     die;
     // just in case! :)
 }
 function goto_tasks_page_for_user()
 {
     $user = Users::findById($this->request->getId('selected_user_id'));
     $page_title = $user->getName() . ' - Task List';
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     mysql_select_db(DB_NAME, $link);
     $query = "select id from healingcrystals_project_objects where type='Page' and project_id='" . TASK_LIST_PROJECT_ID . "' and name='" . mysql_real_escape_string($page_title) . "'";
     $result = mysql_query($query, $link);
     if (mysql_num_rows($result)) {
         $info = mysql_fetch_assoc($result);
         $this->redirectToUrl(assemble_url('project_page', array('project_id' => TASK_LIST_PROJECT_ID, 'page_id' => $info['id'])));
     } else {
         $query = "select id from healingcrystals_project_objects where type='Category' and module='pages' and project_id='" . TASK_LIST_PROJECT_ID . "' and name='General'";
         $page_category = mysql_query($query);
         $page_category_info = mysql_fetch_assoc($page_category);
         $page_data = array('type' => 'Page', 'module' => 'pages', 'visibility' => VISIBILITY_NORMAL, 'name' => $page_title, 'body' => 'Auto-generated Task List Page', 'integer_field_1' => '1');
         db_begin_work();
         $this->active_page = new Page();
         $this->active_page->setAttributes($page_data);
         $this->active_page->setProjectId(TASK_LIST_PROJECT_ID);
         $this->active_page->setCreatedBy($this->logged_user);
         $this->active_page->setState(STATE_VISIBLE);
         $this->active_page->setParentId($page_category_info['id']);
         $save = $this->active_page->save();
         if ($save && !is_error($save)) {
             //$subscribers = array($this->logged_user->getId());
             //if(!in_array($this->active_project->getLeaderId(), $subscribers)) {
             //	$subscribers[] = $this->active_project->getLeaderId();
             //}
             //Subscriptions::subscribeUsers($subscribers, $this->active_page);
             db_commit();
             $this->active_page->ready();
             $query = "select * from healingcrystals_project_users where user_id='" . $user->getId() . "' and project_id='" . TASK_LIST_PROJECT_ID . "'";
             $result = mysql_query($query, $link);
             if (!mysql_num_rows($result)) {
                 //mysql_query("insert into healingcrystals_project_users (user_id, project_id, role_id, permissions) values ('" . $user->getId() . "', '" . TASK_LIST_PROJECT_ID . "', '" . $user->getRoleId() . "', 'N;')");
                 mysql_query("insert into healingcrystals_project_users (user_id, project_id, role_id, permissions) values ('" . $user->getId() . "', '" . TASK_LIST_PROJECT_ID . "', '7', 'N;')");
             } elseif ($user->getRoleId() == '2') {
                 mysql_query("update healingcrystals_project_users set role_id='7' where user_id='" . $user->getId() . "' and project_id='" . TASK_LIST_PROJECT_ID . "'");
             }
             $this->redirectToUrl(assemble_url('project_page', array('project_id' => TASK_LIST_PROJECT_ID, 'page_id' => $this->active_page->getId())));
         } else {
             db_rollback();
             //$save .= 'rollback';
         }
     }
     mysql_close($link);
     $this->smarty->assign(array('user' => $user, 'project' => $this->active_project, 'errors' => $save, 'data' => $page_data));
 }
 /**
  * Delete project and all realted data
  *
  * @param void
  * @return null
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         ProjectObjects::deleteByProject($this);
         ProjectUsers::deleteByProject($this);
         PinnedProjects::deleteByProject($this);
         search_index_remove($this->getId(), 'Project');
         clean_project_permissions_cache($this);
         event_trigger('on_project_deleted', array($this));
         db_commit();
     } else {
         db_rollback();
     }
     // if
     return $delete;
 }
 /**
  * Drop this payment
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $invoice = $this->getInvoice();
     if (!instance_of($invoice, 'Invoice')) {
         return new Error('$invoice is not valid instance of Invoice class', true);
     }
     // if
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         if ($invoice->isBilled() || $invoice->isCanceled()) {
             $invoice->setStatus(INVOICE_STATUS_ISSUED);
             $save = $invoice->save();
             if ($save && !is_error($save)) {
                 db_commit();
                 return true;
             } else {
                 db_rollback();
                 return $save;
             }
             // if
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
 /**
  * Edit Profile Password
  *
  * @param void
  * @return null
  */
 function edit_password()
 {
     $this->wireframe->print_button = false;
     if ($this->active_user->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_user->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $user_data = $this->request->post('user');
     $this->smarty->assign('user_data', $user_data);
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         $password = array_var($user_data, 'password');
         $repeat_password = array_var($user_data, 'repeat_password');
         if (empty($password)) {
             $errors->addError(lang('Password value is required'), 'password');
         }
         // if
         if (empty($repeat_password)) {
             $errors->addError(lang('Repeat Password value is required'), 'repeat_password');
         }
         // if
         if (!$errors->hasErrors() && $password !== $repeat_password) {
             $errors->addError(lang('Inserted values does not match'));
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign('errors', $errors);
             $this->render();
         }
         // if
         db_begin_work();
         $this->active_user->setPassword($user_data['password']);
         $save = $this->active_user->save();
         if ($save && !is_error($save)) {
             db_commit();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_success('Password has been updated');
                 $this->redirectToUrl($this->active_user->getViewUrl());
             } else {
                 $this->serveData($this->active_user, 'user');
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 $this->smarty->assign('errors', $errors);
             } else {
                 $this->serveData($errors);
             }
             // if
         }
         // if
     }
     // if
 }
 /**
  * Show and process edit status form
  *
  * @param void
  * @return null
  */
 function edit_status()
 {
     if ($this->active_project->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND, null, true, $this->request->isApiCall());
     }
     // if
     if ($this->request->isApiCall() && !$this->request->isSubmitted()) {
         $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
     }
     // if
     if (!$this->active_project->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN, null, true, $this->request->isApiCall());
     }
     // if
     $project_data = $this->request->post('project');
     if (!is_array($project_data)) {
         $project_data = array('status' => $this->active_project->getStatus());
     }
     // if
     $this->smarty->assign('project_data', $project_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         switch (array_var($project_data, 'status')) {
             case PROJECT_STATUS_ACTIVE:
                 $save = $this->active_project->reopen();
                 break;
             case PROJECT_STATUS_PAUSED:
                 $save = $this->active_project->reopen(true);
                 break;
             case PROJECT_STATUS_COMPLETED:
                 $save = $this->active_project->complete($this->logged_user);
                 break;
             case PROJECT_STATUS_CANCELED:
                 $save = $this->active_project->complete($this->logged_user, true);
                 break;
             default:
                 $this->httpError(HTTP_ERR_BAD_REQUEST);
         }
         // switch
         if ($save && !is_error($save)) {
             db_commit();
             if ($this->request->isApiCall()) {
                 $this->serveData($this->active_project, 'project');
             } else {
                 flash_success("Status of ':name' project has been updated", array('name' => $this->active_project->getName()));
                 $this->redirectToUrl($this->active_project->getOverviewUrl());
             }
             // if
         } else {
             db_rollback();
             if ($this->request->isApiCall()) {
                 $this->serveData($save);
             } else {
                 $this->smarty->assign('errors', $save);
             }
             // if
         }
         // if
     }
     // if
 }
 /**
  * Delete from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         unlink($this->getAvatarPath());
         unlink($this->getAvatarPath(true));
         ProjectUsers::deleteByUser($this);
         Assignments::deleteByUser($this);
         Subscriptions::deleteByUser($this);
         StarredObjects::deleteByUser($this);
         PinnedProjects::deleteByUser($this);
         UserConfigOptions::deleteByUser($this);
         Reminders::deleteByUser($this);
         search_index_remove($this->getId(), 'User');
         $cleanup = array();
         event_trigger('on_user_cleanup', array(&$cleanup));
         if (is_foreachable($cleanup)) {
             foreach ($cleanup as $table_name => $fields) {
                 foreach ($fields as $field) {
                     $condition = '';
                     if (is_array($field)) {
                         $id_field = array_var($field, 'id');
                         $name_field = array_var($field, 'name');
                         $email_field = array_var($field, 'email');
                         $condition = array_var($field, 'condition');
                     } else {
                         $id_field = $field . '_id';
                         $name_field = $field . '_name';
                         $email_field = $field . '_email';
                     }
                     // if
                     if ($condition) {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ? AND {$condition}", $this->getName(), $this->getEmail(), $this->getId());
                     } else {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ?", $this->getName(), $this->getEmail(), $this->getId());
                     }
                     // if
                 }
                 // foreach
             }
             // foreach
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
 /**
  * Upate time record
  *
  * @param void
  * @return null
  */
 function edit()
 {
     $this->wireframe->print_button = false;
     if ($this->request->isApiCall() && !$this->request->isSubmitted()) {
         $this->httpError(HTTP_ERR_BAD_REQUEST);
     }
     // if
     if ($this->active_time->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_time->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $timetracking_data = $this->request->post('time');
     if (!is_array($timetracking_data)) {
         $timetracking_data = array('user_id' => $this->active_time->getUserId(), 'record_user' => $this->active_time->getUser(), 'value' => $this->active_time->getValue(), 'body' => $this->active_time->getBody(), 'record_date' => $this->active_time->getRecordDate(), 'billable_status' => $this->active_time->getBillableStatus());
     }
     // if
     $this->smarty->assign('timetracking_data', $timetracking_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $timetracking_data['value'] = time_to_float($timetracking_data['value']);
         $old_user_id = $this->active_time->getUserId();
         $this->active_time->setAttributes($timetracking_data);
         if (isset($timetracking_data['user_id']) && $timetracking_data['user_id']) {
             $user_id = array_var($timetracking_data, 'user_id');
             if ($user_id) {
                 $user = Users::findById($user_id);
                 if (instance_of($user, 'User')) {
                     $timetracking_data['record_user'] = $user;
                     if ($user_id != $old_user_id) {
                         $this->active_time->setUser($user);
                     }
                     // if
                 }
                 // if
             }
             // if
         } else {
             if ($user_id == $old_user_id) {
                 $timetracking_data['record_user'] = $this->active_time->getUser();
                 // Not changed anonymous user
             }
             // if
         }
         // if
         $this->smarty->assign('timetracking_data', $timetracking_data);
         $save = $this->active_time->save();
         if ($save && !is_error($save)) {
             db_commit();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_success('Time record #:record_id has been updated', array('record_id' => $this->active_time->getId()));
                 $this->redirectToUrl($this->smarty->get_template_vars('time_url'));
             } else {
                 $this->serveData($this->active_time, 'time_record');
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 $this->smarty->assign('errors', $save);
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
 /**
  * Subscribe array of users to the object
  * 
  * If $replace is set to true, all subscriptions for this object will be 
  * dropped and $users will be subscribed to it
  *
  * @param array $users
  * @param ProjectObject $object
  * @param boolean $replace
  * @return boolean
  */
 function subscribeUsers($users, $object, $replace = true)
 {
     db_begin_work();
     $object_id = (int) $object->getId();
     if ($object_id) {
         $subscriptions_table = TABLE_PREFIX . 'subscriptions';
         if ($replace) {
             Subscriptions::deleteByParent($object);
             // cleanup
         }
         // if
         $to_subscribe = array();
         if (is_foreachable($users)) {
             foreach ($users as $user) {
                 if (instance_of($user, 'User')) {
                     $user_id = (int) $user->getId();
                 } else {
                     $user_id = (int) $user;
                 }
                 // if
                 if ($user_id) {
                     if (isset($to_subscribe[$user_id])) {
                         continue;
                         // duplicate user ID!
                     } else {
                         if (!$replace && array_var(db_execute_one("SELECT COUNT(*) AS 'row_count' FROM {$subscriptions_table} WHERE user_id = ? AND parent_id = ?", $user_id, $object_id), 'row_count') > 0) {
                             continue;
                             // Make sure that we do not have this user already subscribed
                         }
                         // if
                         cache_remove("user_subscriptions_{$user_id}");
                         $to_subscribe[$user_id] = "({$user_id}, {$object_id})";
                     }
                     // if
                 }
                 // if
             }
             // foreach
         }
         // if
         // Insert subscriptions
         if (is_foreachable($to_subscribe)) {
             $insert = db_execute("INSERT INTO {$subscriptions_table} VALUES " . implode(', ', $to_subscribe));
             if (!$insert || is_error($insert)) {
                 db_rollback();
                 return $insert;
             }
             // if
         }
         // if
     }
     // if
     db_commit();
     return true;
 }
 /**
  * Delete document
  * 
  * @param void
  * @return null 
  */
 function delete()
 {
     $filepath = $this->getFilePath();
     db_begin_work();
     $delete = parent::delete();
     if (!$delete || is_error($delete)) {
         db_rollback();
         return $delete;
     }
     // if
     $delete_attachments = Attachments::deleteByObject($this);
     if (!$delete_attachments || is_error($delete_attachments)) {
         db_rollback();
         return $delete_attachments;
     }
     // if
     if (is_file($filepath)) {
         @unlink($filepath);
     }
     // if
     db_commit();
     return true;
 }
 /**
  * Drop invoice
  * invoices shuld not be dropped, only drafts
  *
  * @param void
  * @return null
  */
 function delete()
 {
     if ($this->active_invoice->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_invoice->canDelete($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $delete = $this->active_invoice->delete();
         if ($delete && !is_error($delete)) {
             db_commit();
             flash_success(':invoice has been deleted', array('invoice' => $this->active_invoice->getName()));
         } else {
             db_rollback();
             flash_error('Failed to delete :invoice', array('invoice' => $this->active_invoice->getName()));
         }
         // if
         $this->redirectTo('invoices');
     } else {
         $this->httpError(HTTP_ERR_BAD_REQUEST);
     }
     // if
 }
 /**
  * Show and process edit attachment form
  *
  * @param void
  * @return null
  */
 function edit()
 {
     $this->wireframe->print_button = false;
     if ($this->active_attachment->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $parent = $this->active_attachment->getParent();
     if (!instance_of($parent, 'ProjectObject')) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $attachment_data = $this->request->post('attachment');
     if (!is_array($attachment_data)) {
         $attachment_data = array('name' => $this->active_attachment->getName());
     }
     // if
     $this->smarty->assign('attachment_data', $attachment_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $old_name = $this->active_attachment->getName();
         $this->active_attachment->setName(array_var($attachment_data, 'name'));
         $save = $this->active_attachment->save();
         if ($save && !is_error($save)) {
             db_commit();
             $this->active_attachment->ready();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_success('File :filename has been updated', array('filename' => $old_name));
                 $this->redirectToUrl($parent->getViewUrl());
             } else {
                 $this->serveData($this->active_attachment);
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_error('Failed to update :filename', array('filename' => $old_name));
                 $this->redirectToUrl($parent->getViewUrl());
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
 function quickreminder()
 {
     if ($this->active_task->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND, null, true, $this->request->isApiCall());
     }
     if (empty($this->active_task_parent)) {
         $this->httpError(HTTP_ERR_NOT_FOUND, null, true, $this->request->isApiCall());
     }
     if (!$this->active_task->canEdit($this->logged_user) && $this->active_task->getProjectId() != TASK_LIST_PROJECT_ID) {
         $this->httpError(HTTP_ERR_FORBIDDEN, null, true, $this->request->isApiCall());
     }
     $task_data = $this->request->post('taskquick');
     if (!is_array($task_data)) {
         $task_data = array('body' => $this->active_task->getBody(), 'priority' => $this->active_task->getPriority(), 'due_on' => $this->active_task->getDueOn(), 'assignees' => Assignments::findAssignmentDataByObject($this->active_task));
         $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
         mysql_select_db(DB_NAME);
         $query = "select * from healingcrystals_project_object_misc where object_id='" . $this->active_task->getId() . "'";
         $result = mysql_query($query, $link);
         if (mysql_num_rows($result)) {
             $info = mysql_fetch_assoc($result);
             //$task_data['recurring_flag'] = '1';
             //$task_data['recurring_period'] = $info['recurring_period'];
             //if (empty($task_data['recurring_period'])){
             //   $task_data['recurring_flag'] = '0';
             //}
             //$task_data['recurring_period_type'] = $info['recurring_period_type'];
             //$task_data['recurring_period_condition'] = $info['recurring_period_condition'];
             //$task_data['recurring_end_date'] = empty($info['recurring_end_date']) || $info['recurring_end_date']=='0000-00-00' ? '' : dateval($info['recurring_end_date']);
             if (!empty($info['reminder_date']) && $info['reminder_date'] != '0000-00-00 00:00:00') {
                 list($date, $time) = explode(' ', $info['reminder_date']);
                 list($h, $m, $s) = explode(':', $time);
                 $date = dateval($date);
             }
             $task_data['reminder'] = $date;
             $task_data['remindermeridian'] = $h >= 12 ? 'PM' : 'AM';
             $task_data['reminderhours'] = $h > 12 ? $h - 12 : ($h != 0 ? $h : '12');
             $task_data['reminderminutes'] = $m;
             $task_data['auto_email_status'] = $info['auto_email_status'];
         } else {
             //$task_data['recurring_flag'] = '0';
             //$task_data['recurring_period'] = '';
             //$task_data['recurring_period_type'] = 'D';
             //$task_data['recurring_period_condition'] = 'after_due_date';
             //$task_data['recurring_end_date'] = '';
             $task_data['reminder'] = '';
             $task_data['reminderhours'] = '';
             $task_data['reminderminutes'] = '';
             $task_data['remindermeridian'] = '';
             $task_data['auto_email_status'] = '';
         }
         mysql_close($link);
     }
     $this->smarty->assign('task_data', $task_data);
     $refresh_task_content_mode = false;
     if ($this->request->isSubmitted()) {
         if (!isset($task_data['assignees'])) {
             $task_data['assignees'] = array(array(), 0);
         }
         db_begin_work();
         $old_name = $this->active_task->getBody();
         $this->active_task->setAttributes($task_data);
         $save = $this->active_task->save();
         if ($save && !is_error($save)) {
             db_commit();
             $reminder = dateval($task_data['reminder']);
             $reminderhours = (int) $task_data['reminderhours'];
             $reminderminutes = (int) $task_data['reminderminutes'];
             $remindermeridian = $task_data['remindermeridian'];
             if (!empty($reminder)) {
                 if (!empty($remindermeridian) && $remindermeridian == 'PM' && $reminderhours < 12) {
                     $reminderhours += 12;
                 } elseif (!empty($remindermeridian) && $remindermeridian == 'AM' && $reminderhours == 12) {
                     $reminderhours = 0;
                 }
                 $reminder = $reminder . ' ' . $reminderhours . ':' . $reminderminutes;
             }
             $email_flag = empty($task_data['email_flag']) ? '0' : '1';
             $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             mysql_select_db(DB_NAME);
             $query = "select * from healingcrystals_project_object_misc where object_id='" . $this->active_task->getId() . "'";
             $result = mysql_query($query, $link);
             if (mysql_num_rows($result)) {
                 $query01 = "update healingcrystals_project_object_misc set reminder_date='" . $reminder . "', auto_email_status='" . $email_flag . "', last_modified=now() where object_id='" . $this->active_task->getId() . "'";
                 mysql_query($query01, $link);
             } else {
                 $query01 = "insert into healingcrystals_project_object_misc\n                                    (object_id,\n                                     reminder_date,\n                                     recurring_period,\n                                     recurring_period_type,\n                                     recurring_period_condition,\n                                     recurring_end_date,\n                                     date_added,\n                                     auto_email_status) values\n                                     ('" . $this->active_task->getId() . "',\n                                      '" . $reminder . "',\n                                      null,\n                                      null,\n                                      null,\n                                      null,\n                                      now(),\n                                      '" . $email_flag . "')";
                 mysql_query($query01, $link);
             }
             mysql_close($link);
             /*if($this->request->isApiCall()) {
             			$this->serveData($this->active_task, 'task');
             		} else {
             			flash_success('Task ":name" has been updated', array('name' => str_excerpt(strip_tags($old_name), 80, '...')), false, false);
             			$this->redirectToUrl($this->active_task_parent->getViewUrl() . '#task' . $this->active_task->getId());
             		}*/
             $refresh_task_content_mode = true;
         } else {
             db_rollback();
             if ($this->request->isApiCall()) {
                 $this->serveData($save);
             } else {
                 $this->smarty->assign('errors', $save);
             }
         }
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
         }
     }
     $this->smarty->assign('refresh_task_content_mode', $refresh_task_content_mode);
 }
 /**
  * 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
 }
 /**
  * Upate discussion
  *
  * @param void
  * @return null
  */
 function edit()
 {
     $this->wireframe->print_button = false;
     if ($this->request->isApiCall() && !$this->request->isSubmitted()) {
         $this->httpError(HTTP_ERR_BAD_REQUEST);
     }
     // ifs
     if ($this->active_discussion->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_discussion->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     //BOF:mod 20110615
     $subscribers = $this->active_discussion->getSubscribers();
     $notify_users = array(array(), null);
     foreach ($subscribers as $subscriber) {
         $notify_users[0][] = $subscriber->getId();
     }
     $this->smarty->assign('notify_users', $notify_users);
     //EOF:mod 20110615
     $discussion_data = $this->request->post('discussion');
     if (!is_array($discussion_data)) {
         $discussion_data = array('name' => $this->active_discussion->getName(), 'body' => $this->active_discussion->getBody(), 'parent_id' => $this->active_discussion->getParentId(), 'milestone_id' => $this->active_discussion->getMilestoneId(), 'visibility' => $this->active_discussion->getVisibility(), 'tags' => $this->active_discussion->getTags());
     }
     // if
     $this->smarty->assign('discussion_data', $discussion_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $old_name = $this->active_discussion->getName();
         $this->active_discussion->setAttributes($discussion_data);
         $save = $this->active_discussion->save();
         if ($save && !is_error($save)) {
             db_commit();
             //BOF: mod
             $this->active_discussion->register_departments(!empty($discussion_data['departments']) ? $discussion_data['departments'] : array());
             //EOF: mod
             //BOF:mod 20110614
             $subscribers = $this->request->post('notify_users');
             if (!in_array($this->active_project->getLeaderId(), $subscribers)) {
                 $subscribers[] = $this->active_project->getLeaderId();
             }
             // if
             Subscriptions::subscribeUsers($subscribers, $this->active_discussion);
             $assignees_flag_data = $this->request->post('assignee');
             $this->active_discussion->register_assignees_flag($assignees_flag_data);
             //EOF:mod 20110614
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_success('Discussion ":name" has been updated', array('name' => $old_name));
                 $this->redirectToUrl($this->active_discussion->getViewUrl());
             } else {
                 $this->serveData($this->active_discussion, 'discussion');
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 $this->smarty->assign('errors', $save);
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
 /**
  * Find project objects in commit message, make them links and
  * save the relations to database
  *
  * @param string $commit_message
  * @param string $commit_author
  * @param integer $revision
  * @param Repository $repository
  * @param Project $project
  * @return string
  */
 function analyze_message($commit_message, $commit_author, $revision, $repository, $project)
 {
     if (define('PURIFY_HTML') && PURIFY_HTML) {
         $commit_message = purify_html($commit_message);
         // Clean!
     }
     // if
     $pattern = '/((complete[d]*)[\\s]+)?(ticket|milestone|discussion|task)[s]*[\\s]+[#]*\\d+/i';
     if (preg_match_all($pattern, $commit_message, $matches)) {
         $i = 0;
         $search = array();
         $replace = array();
         $matches_unique = array_unique($matches['0']);
         foreach ($matches_unique as $key => $match) {
             $match_data = preg_split('/[\\s,]+/', $match, null, PREG_SPLIT_NO_EMPTY);
             // check if the object got completed by this commit
             $object_completed = false;
             if (strpos(strtolower($match_data['0']), 'complete') !== false) {
                 $object_completed = true;
                 unset($match_data['0']);
                 $match_data = array_values($match_data);
             }
             // if
             $object_class_name = $match_data['0'];
             $module_name = Inflector::pluralize($object_class_name);
             $object_id = trim($match_data['1'], '#');
             $search[$i] = $match;
             if (class_exists($module_name) && class_exists($object_class_name)) {
                 $object = null;
                 switch (strtolower($module_name)) {
                     case 'tickets':
                         $object = Tickets::findByTicketId($project, $object_id);
                         break;
                     case 'discussions':
                         $object = Discussions::findById($object_id);
                         break;
                     case 'milestones':
                         $object = Milestones::findById($object_id);
                         break;
                     case 'tasks':
                         $object = Tasks::findById($object_id);
                         break;
                 }
                 // switch
                 if (instance_of($object, $object_class_name)) {
                     $link_already_created = CommitProjectObjects::count("object_id = '" . $object->getId() . "' AND revision = '{$revision}'") > 0;
                     if (!$link_already_created) {
                         $comit_project_object = new CommitProjectObject();
                         $comit_project_object->setProjectId($object->getProjectId());
                         $comit_project_object->setObjectId($object->getId());
                         $comit_project_object->setObjectType(ucfirst($object_class_name));
                         $comit_project_object->setRepositoryId($repository->getId());
                         $comit_project_object->setRevision($revision);
                         db_begin_work();
                         $save = $comit_project_object->save();
                         if ($save && !is_error($save)) {
                             db_commit();
                         } else {
                             db_rollback();
                         }
                         // if save
                     }
                     // if
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="' . $object->getViewUrl() . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                     // set the object as completed
                     if ($object_completed && !instance_of($object, 'Discussion')) {
                         $completed_by = $repository->getMappedUser($commit_author);
                         $object->complete($completed_by);
                     }
                     // if
                 } else {
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="#" class="project_object_missing" title="' . lang('Project object does not exist in this project') . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                 }
                 // if instance_of
                 $i++;
             }
             // if module loaded
         }
         // foreach
         return str_ireplace($search, $replace, htmlspecialchars($commit_message));
         // linkify
     }
     // if preg_match
     return $commit_message;
 }
 /**
  * Delete existing invoice from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         InvoiceItems::deleteByInvoice($this);
         InvoicePayments::deleteByInvoice($this);
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
 /**
  * Delete this company from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         cache_remove('companies_id_name');
         // remove ID - name map from cache
         $users = $this->getUsers();
         if (is_foreachable($users)) {
             foreach ($users as $user) {
                 $user->delete();
             }
             // foreach
         }
         // if
         Projects::resetByCompany($this);
         db_commit();
     } else {
         db_rollback();
     }
     // if
     return $delete;
 }
 /**
  * Drop this category
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         $documents = $this->getDocuments();
         foreach ($documents as $document) {
             $document->delete();
         }
         // foreach
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }