예제 #1
2
 static function getCompanyWebsite()
 {
     OgHelper::includeBasic();
     static $first = true;
     $cw = CompanyWebsite::instance();
     if ($first) {
         $cw->init();
         $first = false;
     }
     return $cw;
 }
예제 #2
0
	/**
	 * Init company website environment
	 *
	 * @access public
	 * @param void
	 * @return null
	 * @throws Error
	 */
	function init() {
		if(isset($this) && ($this instanceof CompanyWebsite)) {
			$this->initCompany();
			$this->initLoggedUser();
			$this->initContext();
		} else {
			CompanyWebsite::instance()->init();
		} // if
	} // init
예제 #3
0
 function initUser($id)
 {
     $this->user = Users::findById($id);
     if ($this->user != null) {
         CompanyWebsite::instance()->setLoggedUser($this->user);
     } else {
         ImportLogger::instance()->logError("User not found: id={$id}");
         die("User not found: id={$id}");
     }
 }
예제 #4
0
 /**
  * Init company website environment
  *
  * @access public
  * @param void
  * @return null
  * @throws Error
  */
 function init()
 {
     if (isset($this) && $this instanceof CompanyWebsite) {
         $this->initCompany();
         $this->initActiveProject();
         $this->initLoggedUser();
     } else {
         CompanyWebsite::instance()->init();
     }
     // if
 }
 /**
  * Init company website environment
  *
  * @access public
  * @param void
  * @return null
  * @throws Error
  */
 function init()
 {
     trace(__FILE__, 'init()');
     if (isset($this) && $this instanceof CompanyWebsite) {
         $this->initCompany();
         $this->initActiveProject();
         $controller = array_var($_GET, 'c');
         //Feed users do not need to be logged in here
         if ($controller != 'feed') {
             $this->initLoggedUser();
         }
     } else {
         CompanyWebsite::instance()->init();
     }
     // if
 }
예제 #6
0
/**
 * 
 * @Feng 2.0 - ivazquez 
 * 
 */
function active_context() {
	return CompanyWebsite::instance()->getContext() ;
}
 function reset_password()
 {
     $tok = array_var($_GET, 't');
     $uid = array_var($_GET, 'uid');
     $type_notifier = array_var($_GET, 'type_notifier');
     if (!$tok || !$uid) {
         flash_error(lang('invalid parameters'));
         $this->redirectTo('access', 'login');
     }
     $user = Contacts::findById($uid);
     if (!($user instanceof Contact && $user->isUser()) || $user->getDisabled()) {
         flash_error(lang('user dnx'));
         $this->redirectTo('access', 'login');
     }
     $stok = user_config_option('reset_password', null, $user->getId());
     if (!$stok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $split = explode(";", $stok);
     if (count($split) < 2) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $token = $split[0];
     $timestamp = $split[1];
     if ($timestamp < time()) {
         set_user_config_option('reset_password', '', $user->getId());
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     if ($token != $tok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     tpl_assign('token', $token);
     tpl_assign('user', $user);
     tpl_assign('type_notifier', $type_notifier);
     $new_password = array_var($_POST, 'new_password');
     if ($new_password) {
         $repeat_password = array_var($_POST, 'repeat_password');
         if ($new_password != $repeat_password) {
             flash_error(lang('passwords dont match'));
             return;
         }
         try {
             $user_password = new ContactPassword();
             $user_password->setContactId($user->getId());
             $user_password->password_temp = $new_password;
             $user_password->setPasswordDate(DateTimeValueLib::now());
             $user_password->setPassword(cp_encrypt($new_password, $user_password->getPasswordDate()->getTimestamp()));
             $user_password->save();
             $user->setPassword($new_password);
             $user->setUpdatedOn(DateTimeValueLib::now());
             $user->save();
             set_user_config_option('reset_password', '', $user->getId());
             flash_success(lang('success reset password'));
             CompanyWebsite::instance()->logUserOut();
             $this->redirectTo('access', 'login');
         } catch (Exception $e) {
             flash_error($e->getMessage());
         }
     }
 }
예제 #8
0
<?php

header("Content-Type: text/html; charset=utf-8", true);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
	<!-- script src="http://www.savethedevelopers.org/say.no.to.ie.6.js"></script -->
	<title><?php 
echo clean(CompanyWebsite::instance()->getCompany()->getName()) . ' - ' . PRODUCT_NAME;
?>
</title>
	<?php 
echo link_tag(with_slash(ROOT_URL) . "favicon.ico", "rel", "shortcut icon");
?>
	<?php 
echo add_javascript_to_page("og/app.js");
?>
	<?php 
echo add_javascript_to_page(get_url("access", "get_javascript_translation"));
?>
	<?php 
//echo add_javascript_to_page(with_slash(ROOT_URL) . 'language/' . Localization::instance()->getLocale() . "/lang.js")
?>
	<?php 
echo meta_tag('content-type', 'text/html; charset=utf-8', true);
$version = product_version();
if (defined('COMPRESSED_CSS') && COMPRESSED_CSS) {
    echo stylesheet_tag("ogmin.css");
} else {
    echo stylesheet_tag('website.css');
 /**
  * Delete project
  *
  * @param void
  * @return null
  */
 function delete()
 {
     $this->setTemplate('del_project');
     $this->setLayout('administration');
     $project = Projects::findById(get_id());
     if (!$project instanceof Project) {
         flash_error(lang('project dnx'));
         $this->redirectTo('administration', 'projects');
     }
     // if
     if (!$project->canDelete(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('administration', 'projects'));
     }
     // if
     $delete_data = array_var($_POST, 'deleteProject');
     tpl_assign('project', $project);
     tpl_assign('delete_data', $delete_data);
     if (!is_array($delete_data)) {
         $delete_data = array('really' => 0, 'password' => '');
         // array
         tpl_assign('delete_data', $delete_data);
     } else {
         if ($delete_data['really'] == 1) {
             $password = $delete_data['password'];
             if (trim($password) == '') {
                 tpl_assign('error', new Error(lang('password value missing')));
                 $this->render();
             }
             if (!logged_user()->isValidPassword($password)) {
                 tpl_assign('error', new Error(lang('invalid login data')));
                 $this->render();
             }
             // if
             try {
                 DB::beginWork();
                 $project->delete();
                 CompanyWebsite::instance()->setProject(null);
                 ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_DELETE);
                 DB::commit();
                 flash_success(lang('success delete project', $project->getName()));
             } catch (Exception $e) {
                 DB::rollback();
                 flash_error(lang('error delete project'));
             }
             // try
             $this->redirectTo('administration', 'projects');
         } else {
             flash_error(lang('error delete project'));
             $this->redirectTo('administration', 'projects');
         }
     }
 }
	function total_task_times($report_data = null, $task = null, $csv = null){
		if (!$report_data) {
			$report_data = array_var($_POST, 'report');
			// save selections into session
			$_SESSION['total_task_times_report_data'] = $report_data;
		}
		
		if (array_var($_GET, 'export') == 'csv' || (isset($csv) && $csv == true)){
			$context = build_context_array(array_var($_REQUEST, 'context'));
			CompanyWebsite::instance()->setContext($context);
			$report_data = json_decode(str_replace("'",'"', $_REQUEST['parameters']), true);
			tpl_assign('context', $context);
			$this->setTemplate('total_task_times_csv');
		} else {
			$context = active_context();
		}
		
		$columns = array_var($report_data, 'columns');
		if (!is_array($columns)) $columns = array_var($_POST, 'columns', array());
									
		asort($columns); //sort the array by column order
		foreach($columns as $column => $order){
			if ($order > 0) {
				$newColumn = new ReportColumn();
				//$newColumn->setReportId($newReport->getId());
				if(is_numeric($column)){
					$newColumn->setCustomPropertyId($column);
				}else{
					$newColumn->setFieldName($column);
				}				
			}
		}
	
		$user = Contacts::findById(array_var($report_data, 'user'));
		
		$now = DateTimeValueLib::now();
		$now->advance(logged_user()->getTimezone()*3600, true);
		switch (array_var($report_data, 'date_type')){
			case 1: //Today
				$st = DateTimeValueLib::make(0,0,0,$now->getMonth(),$now->getDay(),$now->getYear());
				$et = DateTimeValueLib::make(23,59,59,$now->getMonth(),$now->getDay(),$now->getYear());break;
			case 2: //This week
				$monday = $now->getMondayOfWeek();
				$nextMonday = $now->getMondayOfWeek()->add('w',1)->add('d',-1);
				$st = DateTimeValueLib::make(0,0,0,$monday->getMonth(),$monday->getDay(),$monday->getYear());
				$et = DateTimeValueLib::make(23,59,59,$nextMonday->getMonth(),$nextMonday->getDay(),$nextMonday->getYear());break;
			case 3: //Last week
				$monday = $now->getMondayOfWeek()->add('w',-1);
				$nextMonday = $now->getMondayOfWeek()->add('d',-1);
				$st = DateTimeValueLib::make(0,0,0,$monday->getMonth(),$monday->getDay(),$monday->getYear());
				$et = DateTimeValueLib::make(23,59,59,$nextMonday->getMonth(),$nextMonday->getDay(),$nextMonday->getYear());break;
			case 4: //This month
				$st = DateTimeValueLib::make(0,0,0,$now->getMonth(),1,$now->getYear());
				$et = DateTimeValueLib::make(23,59,59,$now->getMonth(),1,$now->getYear())->add('M',1)->add('d',-1);break;
			case 5: //Last month
				$now->add('M',-1);
				$st = DateTimeValueLib::make(0,0,0,$now->getMonth(),1,$now->getYear());
				$et = DateTimeValueLib::make(23,59,59,$now->getMonth(),1,$now->getYear())->add('M',1)->add('d',-1);break;
			case 6: //Date interval
				$st = getDateValue(array_var($report_data, 'start_value'));
				$st = $st->beginningOfDay();
				
				$et = getDateValue(array_var($report_data, 'end_value'));
				$et = $et->endOfDay();
				break;
		}
		
		$timeslotType = array_var($report_data, 'timeslot_type', 0);
		$group_by = array();
		for ($i = 1; $i <= 3; $i++){
			if ($timeslotType == 0)
				$gb = array_var($report_data, 'group_by_' . $i);
			else
				$gb = array_var($report_data, 'alt_group_by_' . $i);

			if ($gb != '0') $group_by[] = $gb;
		}
		
		$timeslots = Timeslots::getTaskTimeslots($context, null, $user, $st, $et, array_var($report_data, 'task_id', 0), $group_by, null, null, null, $timeslotType);
		
		$unworkedTasks = null;
		if (array_var($report_data, 'include_unworked') == 'checked') {
			$unworkedTasks = ProjectTasks::getPendingTasks(logged_user(), $workspace);
			tpl_assign('unworkedTasks', $unworkedTasks);
		}
		
		
		$gb_criterias = array();
		foreach ($group_by as $text) {
			if (in_array($text, array('contact_id', 'rel_object_id'))) $gb_criterias[] = array('type' => 'column', 'value' => $text);
			else if (in_array($text, array('milestone_id', 'priority'))) $gb_criterias[] = array('type' => 'assoc_obj', 'fk' => 'rel_object_id', 'value' => $text);
			else if (str_starts_with($text, 'dim_')) $gb_criterias[] = array('type' => 'dimension', 'value' => str_replace_first('dim_', '', $text));
		}
		$grouped_timeslots = groupObjects($gb_criterias, $timeslots);
		
		tpl_assign('columns', $columns);
		tpl_assign('timeslotsArray', array());                        
		tpl_assign('grouped_timeslots', $grouped_timeslots);
		if (array_var($report_data, 'date_type') == 6) {
			$st->advance(logged_user()->getTimezone()*3600, true);
			$et->advance(logged_user()->getTimezone()*3600, true);
		}
		tpl_assign('start_time', $st);
		tpl_assign('end_time', $et);
		tpl_assign('user', $user);
		tpl_assign('post', $report_data);
		tpl_assign('title', lang('task time report'));
		tpl_assign('allow_export', false);
		if (array_var($_GET, 'export') == 'csv' || (isset($csv) && $csv == true)) {
			tpl_assign('template_name', 'total_task_times_csv');
			tpl_assign('is_csv', true);
		}else{
			tpl_assign('template_name', 'total_task_times');
			$this->setTemplate('report_wrapper');
		}
	}
예제 #11
0
// Init flash!
Flash::instance();
$language = config_option('installation_base_language', 'en_us');
if (isset($_GET['language'])) {
    $_SESSION['language'] = $_GET['language'];
    $_GET['language'] = '';
}
if (isset($_SESSION['language'])) {
    $language = $_SESSION['language'];
}
if (!plugin_active('i18n')) {
    Localization::instance()->loadSettings($language, ROOT . '/language');
}
try {
    trace(__FILE__, 'CompanyWebsite::init()');
    CompanyWebsite::init();
    if (config_option('upgrade_check_enabled', false)) {
        VersionChecker::check(false);
    }
    // if
    if (config_option('file_storage_adapter', 'mysql') == FILE_STORAGE_FILE_SYSTEM) {
        trace(__FILE__, 'FileRepository::setBackend() - use file storage');
        FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR));
    } else {
        trace(__FILE__, 'FileRepository::setBackend() - use mysql storage');
        FileRepository::setBackend(new FileRepository_Backend_MySQL(DB::connection()->getLink(), TABLE_PREFIX));
    }
    // if
    PublicFiles::setRepositoryPath(ROOT . '/public/files');
    if (trim(PUBLIC_FOLDER) == '') {
        PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files');
 /**
  * Delete project
  *
  * @param void
  * @return null
  */
 function delete()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $pid = get_id();
     $u = Users::findOne(array("conditions" => "personal_project_id = {$pid}"));
     if ($u) {
         //flash_error("id: $pid, u: ".$u->getId());
         ajx_current("empty");
         flash_error(lang('cannot delete personal project'));
         return;
         //$this->redirectTo('administration', 'projects');
     }
     $project = Projects::findById(get_id());
     if (!$project instanceof Project) {
         flash_error(lang('project dnx'));
         ajx_current("empty");
         return;
         //$this->redirectTo('administration', 'projects');
     }
     // if
     if (!$project->canDelete(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
         //$this->redirectToReferer(get_url('administration', 'projects'));
     }
     // if
     if (!array_var($_GET, 'confirm')) {
         tpl_assign('project', $project);
         $this->setTemplate('pre_delete');
         return;
     }
     ajx_current("empty");
     try {
         $id = $project->getId();
         $name = $project->getName();
         DB::beginWork();
         $project->delete();
         CompanyWebsite::instance()->setProject(null);
         ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_DELETE);
         DB::commit();
         flash_success(lang('success delete project', $project->getName()));
         evt_add("workspace deleted", array("id" => $id, "name" => $name));
         ajx_current("start");
     } catch (Exception $e) {
         DB::rollback();
         flash_error($e->getMessage());
         ajx_current("empty");
     }
     // try
     //$this->redirectTo('administration', 'projects');
 }
예제 #13
0
	protected function logoutUser($username) {
		if (logged_user()->getUsername() == $username) {
			CompanyWebsite::instance()->logUserOut();
		}
	}
 /**
  * Log user by token and ID provided through GET method
  *
  * @param void
  * @return User
  */
 private function loginUserByToken($idname = 'id')
 {
     $user = Users::findById(array_var($_GET, $idname));
     if (!$user instanceof User) {
         header("HTTP/1.0 404 Not Found");
         die;
     }
     // if
     if (!$user->isValidToken(array_var($_GET, 'token'))) {
         header("HTTP/1.0 404 Not Found");
         die;
     }
     // if
     CompanyWebsite::instance()->setLoggedUser($user, false, false, false);
     return $user;
 }
예제 #15
0
	/**
	 * Log user out
	 *
	 * @access public
	 * @param void
	 * @return null
	 */
	function logout() {
		ApplicationLogs::createLog(logged_user(),ApplicationLogs::ACTION_LOGOUT,false,false,true,get_ip_address());
		CompanyWebsite::instance()->logUserOut();
		$this->redirectTo('access', 'login');
	} // logout
 function export_google_calendar()
 {
     $users = ExternalCalendarUsers::findAll(array('conditions' => "sync = 1"));
     foreach ($users as $user) {
         // log user in
         $contact = Contacts::findById($user->getContactId());
         CompanyWebsite::instance()->logUserIn($contact);
         ExternalCalendarController::export_google_calendar_for_user($user);
         CompanyWebsite::instance()->logUserOut();
     }
 }
chdir($argv[1]);
define("CONSOLE_MODE", true);
define('PUBLIC_FOLDER', 'public');
include "init.php";
session_commit();
// we don't need sessions
@set_time_limit(0);
// don't limit execution of cron, if possible
ini_set('memory_limit', '1024M');
Env::useHelper('permissions');
$user_id = array_var($argv, 2);
$token = array_var($argv, 3);
// log user in
$user = Contacts::findById($user_id);
if (!$user instanceof Contact || !$user->isValidToken($token)) {
    die;
}
CompanyWebsite::instance()->setLoggedUser($user, false, false, false);
// get parameters
$member_id = array_var($argv, 4);
$old_parent_id = array_var($argv, 5);
// execute the permissions rebuild
try {
    DB::beginWork();
    do_member_parent_changed_refresh_object_permisssions($member_id, $old_parent_id);
    DB::commit();
} catch (Exception $e) {
    Logger::log("ERROR updating permissions after changing member parent for member ({$member_id})");
    DB::rollback();
}
	public function __construct() {
		$this->cw = OgHelper::getCompanyWebsite() ;
		$this->loggedUser = $this->cw->getLoggedUser() ;
	}	
예제 #19
0
	/**
	 * Execute a report and return results
	 *
	 * @param $id
	 * @param $params
	 *
	 * @return array
	 */
	static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) {
		if (is_null(active_context())) {
			CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
		}
		$results = array();
		$report = self::getReport($id);
		if($report instanceof Report){
			$conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
			$conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
			
			$ot = ObjectTypes::findById($report->getReportObjectTypeId());
			$table = $ot->getTableName();
			
			eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
			eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
			
			$order_by = '';
			if (is_object($params)) {
				$params = get_object_vars($params);				
			}
			
			$report_columns = ReportColumns::getAllReportColumns($id);

			$allConditions = "";
			
			if(count($conditionsFields) > 0){
				foreach($conditionsFields as $condField){
					
					$skip_condition = false;
					$model = $ot->getHandlerClass();
					$model_instance = new $model();
					$col_type = $model_instance->getColumnType($condField->getFieldName());

					$allConditions .= ' AND ';
					$dateFormat = 'm/d/Y';
					if(isset($params[$condField->getId()])){
						$value = $params[$condField->getId()];
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME)
						$dateFormat = user_config_option('date_format');
					} else {
						$value = $condField->getValue();
					}
					if ($value == '' && $condField->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						if($condField->getCondition() == 'like' || $condField->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d');
						}
						if($condField->getCondition() != '%'){
							if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
								$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
							} else {
								if ($condField->getCondition()=='=' || $condField->getCondition()=='<=' || $condField->getCondition()=='>='){
									if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
										$equal = 'datediff('.DB::escape($value).', `'.$condField->getFieldName().'`)=0';
									} else {
										$equal = '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
									}
									switch($condField->getCondition()){
										case '=':
											$allConditions .= $equal;
											break;
										case '<=':
										case '>=':
											$allConditions .= '(`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value).' OR '.$equal.') ';
											break;																
									}										
								} else {
									$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
								}									
							}
						} else {
							$allConditions .= '`'.$condField->getFieldName().'` like '.DB::escape("%$value");
						}
					} else $allConditions .= ' true';
					
				}
			}
			if(count($conditionsCp) > 0){
				$dateFormat = user_config_option('date_format');
				$date_format_tip = date_format_tip($dateFormat);
				
				foreach($conditionsCp as $condCp){
					$cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());

					$skip_condition = false;
					
					if(isset($params[$condCp->getId()."_".$cp->getName()])){
						$value = $params[$condCp->getId()."_".$cp->getName()];
					}else{
						$value = $condCp->getValue();
					}
					if ($value == '' && $condCp->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						$current_condition = ' AND ';
						$current_condition .= 'o.id IN ( SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv WHERE ';
						$current_condition .= ' cpv.custom_property_id = '.$condCp->getCustomPropertyId();
						$fieldType = $object->getColumnType($condCp->getFieldName());

						if($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($cp->getType() == 'date') {
							if ($value == $date_format_tip) continue;
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d H:i:s');
						}
						if($condCp->getCondition() != '%'){
							if ($cp->getType() == 'numeric') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}else if ($cp->getType() == 'boolean') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.$value;
								if (!$value) {
									$current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = '.$condCp->getCustomPropertyId();
								}
							}else{
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}
						}else{
							$current_condition .= ' AND cpv.value like '.DB::escape("%$value");
						}
						$current_condition .= ')';
						$allConditions .= $current_condition;
					}
				}
			}
			
			$select_columns = array('*');
			$join_params = null;
			if ($order_by_col == '') {
				$order_by_col = $report->getOrderBy();
			}
			if (in_array($order_by_col, self::$external_columns)) {
				$original_order_by_col = $order_by_col;
				$order_by_col = 'name_order';
				$join_params = array(
					'table' => Objects::instance()->getTableName(),
					'jt_field' => 'id',
					'e_field' => $original_order_by_col,
					'join_type' => 'left'
				);
				$select_columns = array();
				$tmp_cols = $managerInstance->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "e.$col";
				$tmp_cols = Objects::instance()->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "o.$col";
				$select_columns[] = 'jt.name as name_order';
			}
			if ($order_by_asc == null) $order_by_asc = $report->getIsOrderByAsc();

			if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
				$allConditions .= " AND assigned_to_contact_id = ".logged_user()->getId();
			}
			
			if ($managerInstance) {
				$result = $managerInstance->listing(array(
					"select_columns" => $select_columns,
					"order" => "$order_by_col",
					"order_dir" => ($order_by_asc ? "ASC" : "DESC"),
					"extra_conditions" => $allConditions,
					"join_params" => $join_params
				));
			}else{
				// TODO Performance Killer
				$result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, ($order_by_asc ? "ASC" : "DESC"), $allConditions);
			}
			$objects = $result->objects;
			$totalResults = $result->total;

			$results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults);
		
			$dimensions_cache = array();
			
			foreach($report_columns as $column){
				if ($column->getCustomPropertyId() == 0) {
					$field = $column->getFieldName();
					if (str_starts_with($field, 'dim_')) {
						$dim_id = str_replace("dim_", "", $field);
						$dimension = Dimensions::getDimensionById($dim_id);
						$dimensions_cache[$dim_id] = $dimension;
						$doptions = $dimension->getOptions(true);
						$column_name = $doptions && isset($doptions->useLangs) && $doptions->useLangs ? lang($dimension->getCode()) : $dimension->getName();
						
						$results['columns'][$field] = $column_name;
						$results['db_columns'][$column_name] = $field;
					} else {
						if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
							$column_name = Localization::instance()->lang('field '.$ot->getHandlerClass().' '.$field);
							if (is_null($column_name)) $column_name = lang('field Objects '.$field);
							$results['columns'][$field] = $column_name;
							$results['db_columns'][$column_name] = $field;
						}
					}
				} else {
					$results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
				}
			}
			
			$report_rows = array();
			foreach($objects as &$object){/* @var $object Object */
				$obj_name = $object->getObjectName();
				$icon_class = $object->getIconClass();
				
				$row_values = array('object_type_id' => $object->getObjectTypeId());
				
				if (!$to_print) {
					$row_values['link'] = '<a class="link-ico '.$icon_class.'" title="' . $obj_name . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
				}
				
				foreach($report_columns as $column){
					if ($column->getCustomPropertyId() == 0) {
						
						$field = $column->getFieldName();
						
						if (str_starts_with($field, 'dim_')) {
							$dim_id = str_replace("dim_", "", $field);
							if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
								$dimension = Dimensions::getDimensionById($dim_id);
								$dimensions_cache[$dim_id] = $dimension;
							} else {
								$dimension = array_var($dimensions_cache, $dim_id);
							}
							$members = ObjectMembers::getMembersByObjectAndDimension($object->getId(), $dim_id, " AND om.is_optimization=0");
							
							$value = "";
							foreach ($members as $member) {/* @var $member Member */
								$val = $member->getPath();
								$val .= ($val == "" ? "" : "/") . $member->getName();
								
								if ($value != "") $val = " - $val";
								$value .= $val;
							}
							
							$row_values[$field] = $value;
						} else {
						
							$value = $object->getColumnValue($field);
								
							if ($value instanceof DateTimeValue) {
								$field_type = $managerInstance->columnExists($field) ? $managerInstance->getColumnType($field) : Objects::instance()->getColumnType($field);
								$value = format_value_to_print($field, $value->toMySQL(), $field_type, $report->getReportObjectTypeId());
							}
								
							if(in_array($field, $managerInstance->getExternalColumns())){
								$value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
							} else if ($field != 'link'){
								$value = html_to_text($value);
							}
							if(self::isReportColumnEmail($value)) {
								if(logged_user()->hasMailAccounts()){
									$value = '<a class="internalLink" href="'.get_url('mail', 'add_mail', array('to' => clean($value))).'">'.clean($value).'</a></div>';
								}else{
									$value = '<a class="internalLink" target="_self" href="mailto:'.clean($value).'">'.clean($value).'</a></div>';
								}
							}	
							$row_values[$field] = $value;
						}
					} else {
						
						$colCp = $column->getCustomPropertyId();
						$cp = CustomProperties::getCustomProperty($colCp);
						if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */
							
							$cp_val = CustomPropertyValues::getCustomPropertyValue($object->getId(), $colCp);
							$row_values[$cp->getName()] = $cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : "";
							
							$results['columns'][$colCp] = $cp->getName();
							$results['db_columns'][$cp->getName()] = $colCp;
							
						}
					}
				}
				

				Hook::fire("report_row", $object, $row_values);
				$report_rows[] = $row_values;
			}
			
			if (!$to_print) {
				if (is_array($results['columns'])) {
					array_unshift($results['columns'], '');
				} else {
					$results['columns'] = array('');
				}
				Hook::fire("report_header", $ot, $results['columns']);
			}
			$results['rows'] = $report_rows;
		}

		return $results;
	} //  executeReport
예제 #20
0
 /**
 * Return active project if we are on company website
 *
 * @access public
 * @param void
 * @return Project
 */
 function active_project() {
   return CompanyWebsite::instance()->getProject();
 } // active_project
예제 #21
0
 /**
  * Edit logged user password
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_password()
 {
     $user = Contacts::findById(get_id());
     if (!($user instanceof Contact && $user->isUser()) || $user->getDisabled()) {
         flash_error(lang('user dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$user->canUpdateProfile(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUserUrl();
     }
     // if
     tpl_assign('redirect_to', null);
     $password_data = array_var($_POST, 'password');
     tpl_assign('user', $user);
     if (is_array($password_data)) {
         $old_password = array_var($password_data, 'old_password');
         $new_password = array_var($password_data, 'new_password');
         $new_password_again = array_var($password_data, 'new_password_again');
         try {
             if (!logged_user()->isAdminGroup()) {
                 if (trim($old_password) == '') {
                     throw new Error(lang('old password required'));
                 }
                 // if
                 if (!$user->isValidPassword($old_password)) {
                     throw new Error(lang('invalid old password'));
                 }
                 // if
             }
             // if
             if (trim($new_password) == '') {
                 throw new Error(lang('password value required'));
             }
             // if
             if ($new_password != $new_password_again) {
                 throw new Error(lang('passwords dont match'));
             }
             // if
             $user_password = new ContactPassword();
             $user_password->setContactId(get_id());
             $user_password->password_temp = $new_password;
             $user_password->setPasswordDate(DateTimeValueLib::now());
             $user_password->setPassword(cp_encrypt($new_password, $user_password->getPasswordDate()->getTimestamp()));
             $user_password->save();
             $user->setPassword($new_password);
             $user->setUpdatedOn(DateTimeValueLib::now());
             $user->save();
             if ($user->getId() == logged_user()->getId()) {
                 CompanyWebsite::instance()->logUserIn($user, Cookie::getValue("remember", 0));
             }
             ApplicationLogs::createLog($user, ApplicationLogs::ACTION_EDIT);
             flash_success(lang('success edit user', $user->getUsername()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }
예제 #22
0
<?php header ("Content-Type: text/html; charset=utf-8", true); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
	<title><?php echo clean(CompanyWebsite::instance()->getCompany()->getFirstName()) . ' - ' . PRODUCT_NAME ?></title>
	<?php echo link_tag(with_slash(ROOT_URL)."favicon.ico", "rel", "shortcut icon") ?>
	<?php echo add_javascript_to_page("og/app.js") // loaded first because it's needed for translating?>
	<?php echo add_javascript_to_page(get_url("access", "get_javascript_translation")); ?>
	<!--[if IE 7]>
	<?php echo stylesheet_tag("og/ie7.css"); ?>
	<![endif]-->
	<!--[if IE 8]>
	<?php echo stylesheet_tag("og/ie8.css"); ?>
	<![endif]-->
	
	<?php echo meta_tag('content-type', 'text/html; charset=utf-8', true) ?>
<?php

	$version = product_version();
	if (defined('COMPRESSED_CSS') && COMPRESSED_CSS) {
		echo stylesheet_tag("ogmin.css");
	} else {
		echo stylesheet_tag('website.css');
	}
	
	// Include plguin specif stylesheets
	foreach (Plugins::instance()->getActive() as $p) {
		/* @var $p Plugin */
		$css_file =	PLUGIN_PATH ."/".$p->getSystemName()."/public/assets/css/".$p->getSystemName().".css" ;
		if (is_file($css_file)) {
			echo stylesheet_tag(ROOT_URL."/plugins/".$p->getSystemName()."/public/assets/css/".$p->getSystemName().".css" );
예제 #23
0
chdir(dirname(__FILE__) . '/../..');
define("CONSOLE_MODE", true);
define("PLUGIN_MANAGER_CONSOLE", true);
if (!defined('PUBLIC_FOLDER')) {
    define('PUBLIC_FOLDER', 'public');
}
require_once 'init.php';
if (!isset($argv) || !is_array($argv)) {
    die("There is no input arguments\n");
}
// if
$command = array_var($argv, 1);
$arg1 = array_var($argv, 2);
$usr = Contacts::findOne(array("conditions" => "user_type = (SELECT id FROM " . TABLE_PREFIX . "permission_groups WHERE name='Super Administrator')"));
$usr or die("Super Administrator user not found\n");
CompanyWebsite::instance()->logUserIn($usr);
$ctrl = new PluginController();
trim($command) or die("Command is required \n" . $usage);
if ($command == 'list') {
    foreach ($ctrl->index() as $plg) {
        /* @var $plg Plugin */
        echo "---------------------------------------------\n";
        echo "NAME: \t\t" . $plg->getSystemName() . "\n";
        echo "VERSION: \t" . $plg->getVersion() . "\n";
        echo "STATUS: \t" . ($plg->isInstalled() ? 'Installed ' : 'Uninstalled ') . ($plg->isActive() ? 'Activated ' : 'Inactive ') . "\n";
        if ($plg->updateAvailable()) {
            echo "*** There is a new version of this plugin *** \n";
        }
    }
} else {
    if ($command == 'update_all') {
 /**
  * Clear cookies
  *
  * @access public
  * @param void
  * @return null
  */
 function clear_cookies()
 {
     CompanyWebsite::instance()->logUserOut();
     $this->redirectTo('access', 'login');
 }
예제 #25
0
 /**
  * Execute a report and return results
  *
  * @param $id
  * @param $params
  *
  * @return array
  */
 static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset = 0, $limit = 50, $to_print = false)
 {
     if (is_null(active_context())) {
         CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
     }
     $results = array();
     $report = self::getReport($id);
     $show_archived = false;
     if ($report instanceof Report) {
         $conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
         $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
         $ot = ObjectTypes::findById($report->getReportObjectTypeId());
         $table = $ot->getTableName();
         if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') {
             $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print);
             $report_result = null;
             Hook::fire('replace_execute_report_function', $hook_parameters, $report_result);
             if ($report_result) {
                 return $report_result;
             }
         }
         eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
         eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
         $order_by = '';
         if (is_object($params)) {
             $params = get_object_vars($params);
         }
         $report_columns = ReportColumns::getAllReportColumns($id);
         $allConditions = "";
         $contact_extra_columns = self::get_extra_contact_columns();
         if (count($conditionsFields) > 0) {
             foreach ($conditionsFields as $condField) {
                 if ($condField->getFieldName() == "archived_on") {
                     $show_archived = true;
                 }
                 $skip_condition = false;
                 $model = $ot->getHandlerClass();
                 $model_instance = new $model();
                 $col_type = $model_instance->getColumnType($condField->getFieldName());
                 $allConditions .= ' AND ';
                 $dateFormat = 'm/d/Y';
                 if (isset($params[$condField->getId()])) {
                     $value = $params[$condField->getId()];
                     if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                         $dateFormat = user_config_option('date_format');
                     }
                 } else {
                     $value = $condField->getValue();
                 }
                 if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) {
                     $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value);
                 } else {
                     if ($value == '' && $condField->getIsParametrizable()) {
                         $skip_condition = true;
                     }
                     if (!$skip_condition) {
                         $field_name = $condField->getFieldName();
                         if (in_array($condField->getFieldName(), Objects::getColumns())) {
                             $field_name = 'o`.`' . $condField->getFieldName();
                         }
                         if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') {
                             $value = '%' . $value . '%';
                         }
                         if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                             if ($value == date_format_tip($dateFormat)) {
                                 $value = EMPTY_DATE;
                             } else {
                                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                                 $value = $dtValue->format('Y-m-d');
                             }
                         }
                         if ($condField->getCondition() != '%') {
                             if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
                                 $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                             } else {
                                 if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') {
                                     if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
                                         $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0';
                                     } else {
                                         $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                     }
                                     switch ($condField->getCondition()) {
                                         case '=':
                                             $allConditions .= $equal;
                                             break;
                                         case '<=':
                                         case '>=':
                                             $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') ';
                                             break;
                                     }
                                 } else {
                                     $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                 }
                             }
                         } else {
                             $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}");
                         }
                     } else {
                         $allConditions .= ' true';
                     }
                 }
             }
         }
         if (count($conditionsCp) > 0) {
             $dateFormat = user_config_option('date_format');
             $date_format_tip = date_format_tip($dateFormat);
             foreach ($conditionsCp as $condCp) {
                 $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());
                 $skip_condition = false;
                 if (isset($params[$condCp->getId() . "_" . $cp->getName()])) {
                     $value = $params[$condCp->getId() . "_" . $cp->getName()];
                 } else {
                     $value = $condCp->getValue();
                 }
                 if ($value == '' && $condCp->getIsParametrizable()) {
                     $skip_condition = true;
                 }
                 if (!$skip_condition) {
                     $current_condition = ' AND ';
                     $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE ';
                     $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId();
                     $fieldType = $object->getColumnType($condCp->getFieldName());
                     if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') {
                         $value = '%' . $value . '%';
                     }
                     if ($cp->getType() == 'date') {
                         if ($value == $date_format_tip) {
                             continue;
                         }
                         $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                         $value = $dtValue->format('Y-m-d H:i:s');
                     }
                     if ($condCp->getCondition() != '%') {
                         if ($cp->getType() == 'numeric') {
                             $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                         } else {
                             if ($cp->getType() == 'boolean') {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0');
                                 if (!$value) {
                                     $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId();
                                 }
                             } else {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                             }
                         }
                     } else {
                         $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
                     }
                     $current_condition .= ')';
                     $allConditions .= $current_condition;
                 }
             }
         }
         $select_columns = array('*');
         $join_params = null;
         if ($order_by_col == '') {
             $order_by_col = $report->getOrderBy();
         }
         if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) {
             $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns);
         }
         $original_order_by_col = $order_by_col;
         if (in_array($order_by_col, self::$external_columns)) {
             $order_by_col = 'name_order';
             $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left');
             $select_columns = array();
             $tmp_cols = $managerInstance->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "e.{$col}";
             }
             $tmp_cols = Objects::instance()->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "o.{$col}";
             }
             $select_columns[] = 'jt.name as name_order';
         }
         if ($order_by_asc == null) {
             $order_by_asc = $report->getIsOrderByAsc();
         }
         if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
             $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId();
         }
         if ($managerInstance) {
             if ($order_by_col == "order") {
                 $order_by_col = "`{$order_by_col}`";
             }
             $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params);
             if ($limit > 0) {
                 $listing_parameters["start"] = $offset;
                 $listing_parameters["limit"] = $limit;
             }
             if ($show_archived) {
                 $listing_parameters["archived"] = true;
             }
             $result = $managerInstance->listing($listing_parameters);
         } else {
             // TODO Performance Killer
             $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions);
         }
         $objects = $result->objects;
         $totalResults = $result->total;
         $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults);
         $dimensions_cache = array();
         foreach ($report_columns as $column) {
             if ($column->getCustomPropertyId() == 0) {
                 $field = $column->getFieldName();
                 if (str_starts_with($field, 'dim_')) {
                     $dim_id = str_replace("dim_", "", $field);
                     $dimension = Dimensions::getDimensionById($dim_id);
                     $dimensions_cache[$dim_id] = $dimension;
                     $column_name = $dimension->getName();
                     $results['columns'][$field] = $column_name;
                     $results['db_columns'][$column_name] = $field;
                 } else {
                     if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
                         $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field);
                         if (is_null($column_name)) {
                             $column_name = lang('field Objects ' . $field);
                         }
                         $results['columns'][$field] = $column_name;
                         $results['db_columns'][$column_name] = $field;
                     } else {
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if (in_array($field, $contact_extra_columns)) {
                                 $results['columns'][$field] = lang($field);
                                 $results['db_columns'][lang($field)] = $field;
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'Timeslots') {
                                 if (in_array($field, array('time', 'billing'))) {
                                     $results['columns'][$field] = lang('field Objects ' . $field);
                                     $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                 }
                             } else {
                                 if ($ot->getHandlerClass() == 'MailContents') {
                                     if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                         $results['columns'][$field] = lang('field Objects ' . $field);
                                         $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
             }
         }
         $report_rows = array();
         foreach ($objects as &$object) {
             /* @var $object Object */
             $obj_name = $object->getObjectName();
             $icon_class = $object->getIconClass();
             $row_values = array('object_type_id' => $object->getObjectTypeId());
             if (!$to_print) {
                 $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
             }
             foreach ($report_columns as $column) {
                 if ($column->getCustomPropertyId() == 0) {
                     $field = $column->getFieldName();
                     if (str_starts_with($field, 'dim_')) {
                         $dim_id = str_replace("dim_", "", $field);
                         if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
                             $dimension = Dimensions::getDimensionById($dim_id);
                             $dimensions_cache[$dim_id] = $dimension;
                         } else {
                             $dimension = array_var($dimensions_cache, $dim_id);
                         }
                         $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId();
                         $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0");
                         $value = "";
                         foreach ($members as $member) {
                             /* @var $member Member */
                             $val = $member->getPath();
                             $val .= ($val == "" ? "" : "/") . $member->getName();
                             if ($value != "") {
                                 $val = " - {$val}";
                             }
                             $value .= $val;
                         }
                         $row_values[$field] = $value;
                     } else {
                         if ($object instanceof Timeslot) {
                             if ($field == 'id') {
                                 $value = $object->getObjectId();
                             } else {
                                 $value = $object->getColumnValue($field);
                                 // if it is a task column
                                 if (in_array($field, ProjectTasks::instance()->getColumns())) {
                                     $task = ProjectTasks::findById($object->getRelObjectId());
                                     // if task exists
                                     if ($task instanceof ProjectTask) {
                                         $value = $task->getColumnValue($field);
                                         // if it is an external task column
                                         if (in_array($field, ProjectTasks::instance()->getExternalColumns())) {
                                             $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance());
                                         } else {
                                             // if is a date then use format
                                             if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) {
                                                 $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId());
                                             }
                                         }
                                     }
                                     $results['columns'][$field] = lang('field ProjectTasks ' . $field);
                                     $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field;
                                 }
                             }
                         } else {
                             $value = $object->getColumnValue($field);
                         }
                         if ($value instanceof DateTimeValue) {
                             $dateFormat = user_config_option('date_format');
                             Hook::fire("custom_property_date_format", null, $dateFormat);
                             $tz = logged_user()->getTimezone();
                             if ($object instanceof ProjectTask) {
                                 if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) {
                                     $dateFormat = user_config_option('date_format');
                                     $tz = 0;
                                 }
                             }
                             $value = format_date($value, $dateFormat, $tz * 3600);
                         }
                         if (in_array($field, $managerInstance->getExternalColumns())) {
                             if ($object instanceof Timeslot && $field == 'time') {
                                 $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now());
                                 $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp();
                                 $hours = number_format($seconds / 3600, 2, ',', '.');
                                 $value = $hours;
                                 //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract());
                             } else {
                                 if ($object instanceof Timeslot && $field == 'billing') {
                                     $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling();
                                 } else {
                                     $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
                                 }
                             }
                         } else {
                             if ($field != 'link') {
                                 //$value = html_to_text(html_entity_decode($value));
                                 if ($object->getColumnType($field) == DATA_TYPE_STRING) {
                                     // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters
                                     $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value);
                                     $value = nl2br(strip_tags($value));
                                 }
                             }
                         }
                         if (self::isReportColumnEmail($value)) {
                             if (logged_user()->hasMailAccounts()) {
                                 $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>';
                             } else {
                                 $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>';
                             }
                         }
                         $row_values[$field] = $value;
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if ($managerInstance instanceof Contacts) {
                                 $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId()));
                                 if ($field == "email_address") {
                                     $row_values[$field] = $contact->getEmailAddress();
                                 }
                                 if ($field == "is_user") {
                                     $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany();
                                 }
                                 if ($field == "im_values") {
                                     $str = "";
                                     foreach ($contact->getAllImValues() as $type => $value) {
                                         $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}";
                                     }
                                     $row_values[$field] = $str;
                                 }
                                 if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) {
                                     if ($field == "mobile_phone") {
                                         $row_values[$field] = $contact->getPhoneNumber('mobile', null, false);
                                     } else {
                                         if ($field == "work_phone") {
                                             $row_values[$field] = $contact->getPhoneNumber('work', null, false);
                                         } else {
                                             if ($field == "home_phone") {
                                                 $row_values[$field] = $contact->getPhoneNumber('home', null, false);
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) {
                                     if ($field == "personal_webpage") {
                                         $row_values[$field] = $contact->getWebpageUrl('personal');
                                     } else {
                                         if ($field == "work_webpage") {
                                             $row_values[$field] = $contact->getWebpageUrl('work');
                                         } else {
                                             if ($field == "other_webpage") {
                                                 $row_values[$field] = $contact->getWebpageUrl('other');
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("home_address", "work_address", "other_address"))) {
                                     if ($field == "home_address") {
                                         $row_values[$field] = $contact->getStringAddress('home');
                                     } else {
                                         if ($field == "work_address") {
                                             $row_values[$field] = $contact->getStringAddress('work');
                                         } else {
                                             if ($field == "other_address") {
                                                 $row_values[$field] = $contact->getStringAddress('other');
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'MailContents') {
                                 if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                     $mail_data = MailDatas::findById($object->getId());
                                     $row_values[$field] = $mail_data->getColumnValue($field);
                                     if ($field == "body_html") {
                                         if (class_exists("DOMDocument")) {
                                             $d = new DOMDocument();
                                             $mock = new DOMDocument();
                                             $d->loadHTML(remove_css_and_scripts($row_values[$field]));
                                             $body = $d->getElementsByTagName('body')->item(0);
                                             foreach ($body->childNodes as $child) {
                                                 $mock->appendChild($mock->importNode($child, true));
                                             }
                                             // if css is inside an html comment => remove it
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field]));
                                         } else {
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field]));
                                         }
                                     }
                                 }
                             }
                         }
                         if (!$to_print && $field == "name") {
                             $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>';
                         }
                     }
                 } else {
                     $colCp = $column->getCustomPropertyId();
                     $cp = CustomProperties::getCustomProperty($colCp);
                     if ($cp instanceof CustomProperty) {
                         /* @var $cp CustomProperty */
                         $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object);
                         $results['columns'][$colCp] = $cp->getName();
                         $results['db_columns'][$cp->getName()] = $colCp;
                     }
                 }
             }
             Hook::fire("report_row", $object, $row_values);
             $report_rows[] = $row_values;
         }
         if (!$to_print) {
             if (is_array($results['columns'])) {
                 array_unshift($results['columns'], '');
             } else {
                 $results['columns'] = array('');
             }
             Hook::fire("report_header", $ot, $results['columns']);
         }
         $results['rows'] = $report_rows;
     }
     return $results;
 }
 function total_task_times($report_data = null, $task = null, $csv = null)
 {
     if (!$report_data) {
         $report_data = array_var($_POST, 'report');
         set_user_config_option('timeReportDate', $report_data['date_type'], logged_user()->getId());
         $dateStart = getDateValue($report_data['start_value']);
         if ($dateStart instanceof DateTimeValue) {
             set_user_config_option('timeReportDateStart', $dateStart, logged_user()->getId());
         }
         $dateEnd = getDateValue($report_data['end_value']);
         if ($dateEnd instanceof DateTimeValue) {
             set_user_config_option('timeReportDateEnd', $dateEnd, logged_user()->getId());
         }
         set_user_config_option('timeReportShowEstimatedTime', array_var($report_data, 'show_estimated_time') == 'checked', logged_user()->getId());
         set_user_config_option('timeReportPerson', $report_data['user'], logged_user()->getId());
         set_user_config_option('timeReportTimeslotType', $report_data['timeslot_type'], logged_user()->getId());
         set_user_config_option('timeReportShowBilling', isset($report_data['show_billing']) ? 1 : 0, logged_user()->getId());
         $group = $report_data['group_by_1'] . ", " . $report_data['group_by_2'] . ", " . $report_data['group_by_3'];
         $altGroup = $report_data['alt_group_by_1'] . "," . $report_data['alt_group_by_2'] . "," . $report_data['alt_group_by_3'];
         set_user_config_option('timeReportGroupBy', $group, logged_user()->getId());
         set_user_config_option('timeReportAltGroupBy', $altGroup, logged_user()->getId());
         $_SESSION['total_task_times_report_data'] = $report_data;
     }
     if (array_var($_GET, 'export') == 'csv' || isset($csv) && $csv == true) {
         $context = build_context_array(array_var($_REQUEST, 'context'));
         CompanyWebsite::instance()->setContext($context);
         if (!$report_data) {
             if (isset($_REQUEST['parameters'])) {
                 $report_data = json_decode(str_replace("'", '"', $_REQUEST['parameters']), true);
             } else {
                 $report_data = $_REQUEST;
             }
         }
         tpl_assign('context', $context);
         $this->setTemplate('total_task_times_csv');
     } else {
         $context = active_context();
     }
     $columns = array_var($report_data, 'columns');
     if (!is_array($columns)) {
         $columns = array_var($_POST, 'columns', array());
     }
     asort($columns);
     //sort the array by column order
     foreach ($columns as $column => $order) {
         if ($order > 0) {
             $newColumn = new ReportColumn();
             //$newColumn->setReportId($newReport->getId());
             if (is_numeric($column)) {
                 $newColumn->setCustomPropertyId($column);
             } else {
                 $newColumn->setFieldName($column);
             }
         }
     }
     $user = Contacts::findById(array_var($report_data, 'user'));
     $now = DateTimeValueLib::now();
     $now->advance(logged_user()->getTimezone() * 3600, true);
     switch (array_var($report_data, 'date_type')) {
         case 1:
             //Today
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), $now->getDay(), $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), $now->getDay(), $now->getYear());
             break;
         case 2:
             //This week
             $monday = $now->getMondayOfWeek();
             $nextMonday = $now->getMondayOfWeek()->add('w', 1)->add('d', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear());
             break;
         case 3:
             //Last week
             $monday = $now->getMondayOfWeek()->add('w', -1);
             $nextMonday = $now->getMondayOfWeek()->add('d', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear());
             break;
         case 4:
             //This month
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1);
             break;
         case 5:
             //Last month
             $now->add('M', -1);
             $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear());
             $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1);
             break;
         case 6:
             //Date interval
             $st = getDateValue(array_var($report_data, 'start_value'));
             $st = $st->beginningOfDay();
             $et = getDateValue(array_var($report_data, 'end_value'));
             $et = $et->endOfDay();
             break;
     }
     if ($st instanceof DateTimeValue) {
         $st->add('h', -logged_user()->getTimezone());
     }
     if ($et instanceof DateTimeValue) {
         $et->add('h', -logged_user()->getTimezone());
     }
     $timeslotType = array_var($report_data, 'timeslot_type', 0);
     $group_by = array();
     for ($i = 1; $i <= 3; $i++) {
         if ($timeslotType == 0) {
             $gb = array_var($report_data, 'group_by_' . $i);
         } else {
             $gb = array_var($report_data, 'alt_group_by_' . $i);
         }
         if ($gb != '0') {
             $group_by[] = $gb;
         }
     }
     $dateFormat = user_config_option('date_format');
     $date_format_tip = date_format_tip($dateFormat);
     $extra_conditions = "";
     $conditions = array_var($_POST, 'conditions', array());
     foreach ($conditions as $cond) {
         if ($cond['deleted'] > 0) {
             continue;
         }
         if (array_var($cond, 'custom_property_id') > 0) {
             if (!in_array($cond['condition'], array('like', 'not like', '=', '<=', '>=', '<', '>', '<>', '%'))) {
                 continue;
             }
             $cp = CustomProperties::getCustomProperty($cond['custom_property_id']);
             if (!$cp instanceof CustomProperty) {
                 continue;
             }
             $current_condition = ' AND e.rel_object_id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE cpv.custom_property_id = ' . $cond['custom_property_id'];
             $value = $cond['value'];
             if ($cond['condition'] == 'like' || $cond['condition'] == 'not like') {
                 $value = '%' . $cond['value'] . '%';
             }
             if ($cp->getType() == 'date') {
                 if ($value == $date_format_tip) {
                     continue;
                 }
                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                 $value = $dtValue->format('Y-m-d H:i:s');
             }
             if ($cond['condition'] != '%') {
                 if ($cp->getType() == 'numeric') {
                     $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . DB::escape($value);
                 } else {
                     if ($cp->getType() == 'boolean') {
                         $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . ($value ? '1' : '0');
                         if (!$value) {
                             $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $cp->getId();
                         }
                     } else {
                         $current_condition .= ' AND cpv.value ' . $cond['condition'] . ' ' . DB::escape($value);
                     }
                 }
             } else {
                 $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
             }
             $current_condition .= ')';
             $extra_conditions .= $current_condition;
         }
     }
     $timeslots = Timeslots::getTaskTimeslots($context, null, $user, $st, $et, array_var($report_data, 'task_id', 0), $group_by, null, null, null, $timeslotType, $extra_conditions);
     $unworkedTasks = null;
     if (array_var($report_data, 'include_unworked') == 'checked') {
         $unworkedTasks = ProjectTasks::getPendingTasks(logged_user(), $workspace);
         tpl_assign('unworkedTasks', $unworkedTasks);
     }
     $gb_criterias = array();
     foreach ($group_by as $text) {
         if (in_array($text, array('contact_id', 'rel_object_id'))) {
             $gb_criterias[] = array('type' => 'column', 'value' => $text);
         } else {
             if (in_array($text, array('milestone_id', 'priority'))) {
                 $gb_criterias[] = array('type' => 'assoc_obj', 'fk' => 'rel_object_id', 'value' => $text);
             } else {
                 if (str_starts_with($text, 'dim_')) {
                     $gb_criterias[] = array('type' => 'dimension', 'value' => str_replace_first('dim_', '', $text));
                 }
             }
         }
     }
     $grouped_timeslots = groupObjects($gb_criterias, $timeslots);
     tpl_assign('columns', $columns);
     tpl_assign('timeslotsArray', array());
     tpl_assign('grouped_timeslots', $grouped_timeslots);
     if (array_var($report_data, 'date_type') == 6) {
         $st->advance(logged_user()->getTimezone() * 3600, true);
         $et->advance(logged_user()->getTimezone() * 3600, true);
     }
     tpl_assign('start_time', $st);
     tpl_assign('end_time', $et);
     tpl_assign('user', $user);
     tpl_assign('post', $report_data);
     tpl_assign('title', lang('task time report'));
     tpl_assign('allow_export', false);
     if (array_var($_GET, 'export') == 'csv' || isset($csv) && $csv == true) {
         $filename = $this->total_task_times_csv_export($grouped_timeslots);
         ajx_extra_data(array('filename' => "{$filename}.csv"));
         ajx_current("empty");
     } else {
         tpl_assign('template_name', 'total_task_times');
         $this->setTemplate('report_wrapper');
     }
 }