/**
  * Adds the custom properties of an object into the database.
  * 
  * @param $object
  * @return unknown_type
  */
 function add_custom_properties($object)
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $obj_custom_properties = array_var($_POST, 'object_custom_properties');
     $customProps = CustomProperties::getAllCustomPropertiesByObjectType($object->getObjectTypeId());
     //Sets all boolean custom properties to 0. If any boolean properties are returned, they are subsequently set to 1.
     foreach ($customProps as $cp) {
         if ($cp->getType() == 'boolean') {
             $custom_property_value = CustomPropertyValues::getCustomPropertyValue($object->getId(), $cp->getId());
             if (!$custom_property_value instanceof CustomPropertyValue) {
                 $custom_property_value = new CustomPropertyValue();
             }
             $custom_property_value->setObjectId($object->getId());
             $custom_property_value->setCustomPropertyId($cp->getId());
             $custom_property_value->setValue(0);
             $custom_property_value->save();
         }
     }
     if (is_array($obj_custom_properties)) {
         foreach ($obj_custom_properties as $id => $value) {
             //Get the custom property
             $custom_property = null;
             foreach ($customProps as $cp) {
                 if ($cp->getId() == $id) {
                     $custom_property = $cp;
                     break;
                 }
             }
             if ($custom_property instanceof CustomProperty) {
                 // save dates in standard format "Y-m-d H:i:s", because the column type is string
                 if ($custom_property->getType() == 'date') {
                     if (is_array($value)) {
                         $newValues = array();
                         foreach ($value as $val) {
                             $dtv = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $val);
                             $newValues[] = $dtv->format("Y-m-d H:i:s");
                         }
                         $value = $newValues;
                     } else {
                         $dtv = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value);
                         $value = $dtv->format("Y-m-d H:i:s");
                     }
                 }
                 //Save multiple values
                 if (is_array($value)) {
                     CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $id);
                     foreach ($value as &$val) {
                         if (is_array($val)) {
                             // CP type == table
                             $str_val = '';
                             foreach ($val as $col_val) {
                                 $col_val = str_replace("|", "\\|", $col_val);
                                 $str_val .= ($str_val == '' ? '' : '|') . $col_val;
                             }
                             $val = $str_val;
                         }
                         if ($val != '') {
                             if (strpos($val, ',')) {
                                 $val = str_replace(',', '|', $val);
                             }
                             $custom_property_value = new CustomPropertyValue();
                             $custom_property_value->setObjectId($object->getId());
                             $custom_property_value->setCustomPropertyId($id);
                             $custom_property_value->setValue($val);
                             $custom_property_value->save();
                         }
                     }
                 } else {
                     if ($custom_property->getType() == 'boolean') {
                         $value = isset($value);
                     }
                     $cpv = CustomPropertyValues::getCustomPropertyValue($object->getId(), $id);
                     if ($cpv instanceof CustomPropertyValue) {
                         $custom_property_value = $cpv;
                     } else {
                         $custom_property_value = new CustomPropertyValue();
                     }
                     $custom_property_value->setObjectId($object->getId());
                     $custom_property_value->setCustomPropertyId($id);
                     $custom_property_value->setValue($value);
                     $custom_property_value->save();
                 }
                 //Add to searchable objects
                 if ($object->isSearchable() && ($custom_property->getType() == 'text' || $custom_property->getType() == 'list' || $custom_property->getType() == 'numeric')) {
                     $name = $custom_property->getName();
                     $searchable_object = SearchableObjects::findOne(array("conditions" => "`rel_object_id` = " . $object->getId() . " AND `column_name` = '{$name}'"));
                     if (!$searchable_object) {
                         $searchable_object = new SearchableObject();
                     }
                     if (is_array($value)) {
                         $value = implode(', ', $value);
                     }
                     $searchable_object->setRelObjectId($object->getId());
                     $searchable_object->setColumnName($name);
                     $searchable_object->setContent($value);
                     $searchable_object->save();
                 }
             }
         }
     }
 }
                    $task = $ts->getObject();
                    if (!is_numeric($i)) {
                        //for normal properties
                        //currently disabled as at the moment the only columns that can be added are custom properties
                        $value = format_value_to_print_task($task->getColumnValue($i), $task->getColumnType($i));
                        ?>
<td style="padding:4px;max-width:250px;<?php 
                        echo $isAlt ? 'background-color:#F2F2F2' : '';
                        ?>
"><?php 
                        echo $value;
                        ?>
</td><?php 
                    } else {
                        //for custom properties
                        $values = CustomPropertyValues::getCustomPropertyValue($task->getId(), $i);
                        if ($values != null) {
                            $cp = CustomProperties::getCustomProperty($i);
                            $value = format_value_to_print_task($values->getValue(), $cp->getOgType());
                            ?>
<td style="padding:4px;max-width:250px;<?php 
                            echo $isAlt ? 'background-color:#F2F2F2' : '';
                            ?>
"><?php 
                            echo $value;
                            ?>
</td><?php 
                        } else {
                            ?>
<td style="padding:4px;max-width:250px;<?php 
                            echo $isAlt ? 'background-color:#F2F2F2' : '';
	function list_files() {
		
		ajx_current("empty");
		// get query parameters 
		$start = (integer)array_var($_GET,'start');
		$limit = (integer)array_var($_GET,'limit');
		if (! $start) {
			$start = 0;
		}
		if (! $limit) {
			$limit = config_option('files_per_page');
		}
		$order = array_var($_GET,'sort');
		$order_dir = array_var($_GET,'dir');
		$page = (integer) ($start / $limit)+1;
		$hide_private = !logged_user()->isMemberOfOwnerCompany();
		$type = array_var($_GET,'type');
		$user = array_var($_GET,'user');

		// if there's an action to execute, do so 
		if (array_var($_GET, 'action') == 'delete') {
			$ids = explode(',', array_var($_GET, 'objects'));
			$succ = 0; $err = 0;
			foreach ($ids as $id) {
				$file = ProjectFiles::findById($id);
				if (isset($file) && $file->canDelete(logged_user())) {
					try{
						DB::beginWork();
						$file->trash();
						ApplicationLogs::createLog($file, ApplicationLogs::ACTION_TRASH);
						DB::commit();
						$succ++;
					} catch(Exception $e){
						DB::rollback();
						$err++;
					}
				} else {
					$err++;
				}
			}
			if ($succ > 0) {
				flash_success(lang("success delete files", $succ));
			} else {
				flash_error(lang("error delete files", $err));
			}

		} else if (array_var($_GET, 'action') == 'markasread') {
			$ids = explode(',', array_var($_GET, 'objects'));
			$succ = 0; $err = 0;
				foreach ($ids as $id) {
				$file = ProjectFiles::findById($id);
					try {
						$file->setIsRead(logged_user()->getId(),true);
						$succ++;
						
					} catch(Exception $e) {
						$err ++;
					} // try
				}//for
			if ($succ <= 0) {
				flash_error(lang("error markasread files", $err));
			}
		}else if (array_var($_GET, 'action') == 'markasunread') {
			$ids = explode(',', array_var($_GET, 'objects'));
			$succ = 0; $err = 0;
				foreach ($ids as $id) {
				$file = ProjectFiles::findById($id);
					try {
						$file->setIsRead(logged_user()->getId(),false);
						$succ++;

					} catch(Exception $e) {
						$err ++;
					} // try
				}//for
			if ($succ <= 0) {
				flash_error(lang("error markasunread files", $err));
			}
		}
		 else if (array_var($_GET, 'action') == 'zip_add') {
			$this->zip_add();
		} else if (array_var($_GET, 'action') == 'archive') {
			$ids = explode(',', array_var($_GET, 'ids'));
			$succ = 0; $err = 0;
			foreach ($ids as $id) {
				$file = ProjectFiles::findById($id);
				if (isset($file) && $file->canEdit(logged_user())) {
					try{
						DB::beginWork();
						$file->archive();
						ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ARCHIVE);
						DB::commit();
						$succ++;
					} catch(Exception $e){
						DB::rollback();
						$err++;
					}
				} else {
					$err++;
				}
			}
			if ($succ > 0) {
				flash_success(lang("success archive objects", $succ));
			} else {
				flash_error(lang("error archive objects", $err));
			}
		}
		
		Hook::fire('classify_action', null, $ret);		
		$join_params = null;
		
		if ($order == ProjectFiles::ORDER_BY_POSTTIME) {
			$order = '`created_on`';
		} else if ($order == ProjectFiles::ORDER_BY_MODIFYTIME) {
			$order = '`updated_on`';
		} else if ($order == ProjectFiles::ORDER_BY_SIZE) {
			$order = '`jt`.`filesize`';
			$join_params = array(
				'table' => ProjectFileRevisions::instance()->getTableName(),
				'jt_field' => 'object_id',
				'j_sub_q' => "SELECT max(`x`.`object_id`) FROM ".ProjectFileRevisions::instance()->getTableName()." `x` WHERE `x`.`file_id` = `e`.`object_id`"
			);
		} else {
			$order = '`name`';
		} // if
		
		$extra_conditions = $hide_private ? 'AND `is_visible` = 1' : '';
		
		$context = active_context();
		$objects = ProjectFiles::instance()->listing(array(
			"order"=>$order,
			"order_dir" => $order_dir,
			"extra_conditions"=> $extra_conditions,
			"join_params"=> $join_params,
			"start"=> $start,
			"limit"=> $limit
		));
		
		
		$custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectFiles::instance()->getObjectTypeId());
		
		// prepare response object 
		$listing = array(
			"totalCount" => $objects->total,
			"start" => $start,
			"objType" => ProjectFiles::instance()->getObjectTypeId(),
			"files" => array(),
		);
		
		if (is_array($objects->objects)) {
			$index = 0;
			$ids = array();
			foreach ($objects->objects as $o) {
				$coName = "";
				$coId = $o->getCheckedOutById();
				if ($coId != 0) {
					if ($coId == logged_user()->getId()) {
						$coName = "self";
					} else {
						$coUser = Contacts::findById($coId);
						if ($coUser instanceof Contact) {
							$coName = $coUser->getUsername();
						} else {
							$coName = "";
						}
					}
				}

				if ($o->isMP3()) {
					$songname = $o->getProperty("songname");
					$artist = $o->getProperty("songartist");
					$album = $o->getProperty("songalbum");
					$track = $o->getProperty("songtrack");
					$year = $o->getProperty("songyear");
					$duration = $o->getProperty("songduration");
					$songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId()));
				} else {
					$songInfo = array();
				}
				
				$ids[] = $o->getId();
				$values = array(
					"id" => $o->getId(),
					"ix" => $index++,
					"object_id" => $o->getId(),
					"ot_id" => $o->getObjectTypeId(),
					"name" => $o->getObjectName(),
					"type" => $o->getTypeString(),
					"mimeType" => $o->getTypeString(),
					"createdBy" => clean($o->getCreatedByDisplayName()),
					"createdById" => $o->getCreatedById(),
					"dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? ($o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn())) : '',
					"dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0,
					"updatedBy" => clean($o->getUpdatedByDisplayName()),
					"updatedById" => $o->getUpdatedById(),
					"dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? ($o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn())) : '',
					"dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0,
					"icon" => $o->getTypeIconUrl(),
					"size" => format_filesize($o->getFileSize()),
					"url" => $o->getOpenUrl(),
					"manager" => get_class($o->manager()),
					"checkedOutByName" => $coName,
					"checkedOutById" => $coId,
					"isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()),
					"modifyUrl" => $o->getModifyUrl(),
					"songInfo" => $songInfo,
					"ftype" => $o->getType(),
					"url" => $o->getUrl(),
					"memPath" => json_encode($o->getMembersToDisplayPath()),
				);
				if ($o->isMP3()) {
					$values['isMP3'] = true;
				}
				Hook::fire('add_classification_value', $o, $values);
				
				foreach ($custom_properties as $cp) {
					$cp_value = CustomPropertyValues::getCustomPropertyValue($o->getId(), $cp->getId());
					$values['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : '';
				}
				
				$listing["files"][] = $values;
			}
			
			$read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
			foreach($listing["files"] as &$data) {
				$data['isRead'] = isset($read_objects[$data['object_id']]);
			}
			
			ajx_extra_data($listing);
			tpl_assign("listing", $listing);
		}else{
			throw new Error("Not array", $code);			
		}
	}
 function cloneTask($new_st_date = '', $new_due_date = '', $copy_status = false, $copy_repeat_options = true, $parent_subtask = 0)
 {
     $new_task = new TemplateTask();
     if ($parent_subtask != 0) {
         $new_task->setParentId($parent_subtask);
     } else {
         $new_task->setParentId($this->getParentId());
     }
     $new_task->setObjectName($this->getObjectName());
     $new_task->setText($this->getText());
     $new_task->setAssignedToContactId($this->getAssignedToContactId());
     $new_task->setAssignedOn($this->getAssignedOn());
     $new_task->setAssignedById($this->getAssignedById());
     $new_task->setTimeEstimate($this->getTimeEstimate());
     $new_task->setStartedOn($this->getStartedOn());
     $new_task->setStartedById($this->getStartedById());
     $new_task->setPriority($this->getPriority());
     $new_task->setState($this->getState());
     $new_task->setOrder($this->getOrder());
     $new_task->setMilestoneId($this->getMilestoneId());
     $new_task->setFromTemplateId($this->getFromTemplateId());
     $new_task->setUseStartTime($this->getUseStartTime());
     $new_task->setUseDueTime($this->getUseDueTime());
     $new_task->setTypeContent($this->getTypeContent());
     if ($this->getParentId() == 0) {
         //if not subtask
         if ($this->getOriginalTaskId() == 0) {
             $new_task->setOriginalTaskId($this->getObjectId());
         } else {
             $new_task->setOriginalTaskId($this->getOriginalTaskId());
         }
     }
     if ($this->getDueDate() instanceof DateTimeValue) {
         $new_task->setDueDate(new DateTimeValue($this->getDueDate()->getTimestamp()));
     }
     if ($this->getStartDate() instanceof DateTimeValue) {
         $new_task->setStartDate(new DateTimeValue($this->getStartDate()->getTimestamp()));
     }
     if ($copy_status) {
         $new_task->setCompletedById($this->getCompletedById());
         $new_task->setCompletedOn($this->getCompletedOn());
     }
     if ($copy_repeat_options) {
         $new_task->setRepeatEnd($this->getRepeatEnd());
         $new_task->setRepeatForever($this->getRepeatForever());
         $new_task->setRepeatNum($this->getRepeatNum());
         $new_task->setRepeatBy($this->getRepeatBy());
         $new_task->setRepeatD($this->getRepeatD());
         $new_task->setRepeatM($this->getRepeatM());
         $new_task->setRepeatY($this->getRepeatY());
     }
     if ($new_st_date != "") {
         if ($new_task->getStartDate() instanceof DateTimeValue) {
             $new_task->setStartDate($new_st_date);
         }
     }
     if ($new_due_date != "") {
         if ($new_task->getDueDate() instanceof DateTimeValue) {
             $new_task->setDueDate($new_due_date);
         }
     }
     $new_task->save();
     if (is_array($this->getAllLinkedObjects())) {
         foreach ($this->getAllLinkedObjects() as $lo) {
             $new_task->linkObject($lo);
         }
     }
     $sub_tasks = $this->getAllSubTasks();
     foreach ($sub_tasks as $st) {
         $new_dates = $this->getNextRepetitionDatesSubtask($st, $new_task, $new_st_date, $new_due_date);
         if ($st->getParentId() == $this->getId()) {
             $new_st = $st->cloneTask(array_var($new_dates, 'st'), array_var($new_dates, 'due'), $copy_status, $copy_repeat_options, $new_task->getId());
             if ($copy_status) {
                 $new_st->setCompletedById($st->getCompletedById());
                 $new_st->setCompletedOn($st->getCompletedOn());
                 $new_st->save();
             }
             $new_task->attachTask($new_st);
         }
     }
     foreach ($this->getAllComments() as $com) {
         $new_com = new Comment();
         $new_com->setAuthorEmail($com->getAuthorEmail());
         $new_com->setAuthorName($com->getAuthorName());
         $new_com->setAuthorHomepage($com->getAuthorHomepage());
         $new_com->setCreatedById($com->getCreatedById());
         $new_com->setCreatedOn($com->getCreatedOn());
         $new_com->setUpdatedById($com->getUpdatedById());
         $new_com->setUpdatedOn($com->getUpdatedOn());
         $new_com->setText($com->getText());
         $new_com->setRelObjectId($new_task->getId());
         $new_com->save();
     }
     $_POST['subscribers'] = array();
     foreach ($this->getSubscribers() as $sub) {
         $_POST['subscribers']["user_" . $sub->getId()] = "checked";
     }
     $obj_controller = new ObjectController();
     $obj_controller->add_to_members($new_task, $this->getMemberIds());
     $obj_controller->add_subscribers($new_task);
     foreach ($this->getCustomProperties() as $prop) {
         $new_prop = new ObjectProperty();
         $new_prop->setRelObjectId($new_task->getId());
         $new_prop->setPropertyName($prop->getPropertyName());
         $new_prop->setPropertyValue($prop->getPropertyValue());
         $new_prop->save();
     }
     $custom_props = CustomProperties::getAllCustomPropertiesByObjectType("TemplateTasks");
     foreach ($custom_props as $c_prop) {
         $values = CustomPropertyValues::getCustomPropertyValues($this->getId(), $c_prop->getId());
         if (is_array($values)) {
             foreach ($values as $val) {
                 $cp = new CustomPropertyValue();
                 $cp->setObjectId($new_task->getId());
                 $cp->setCustomPropertyId($val->getCustomPropertyId());
                 $cp->setValue($val->getValue());
                 $cp->save();
             }
         }
     }
     $reminders = ObjectReminders::getByObject($this);
     foreach ($reminders as $reminder) {
         $copy_reminder = new ObjectReminder();
         $copy_reminder->setContext($reminder->getContext());
         $reminder_date = $new_task->getColumnValue($reminder->getContext());
         if ($reminder_date instanceof DateTimeValue) {
             $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
             $reminder_date->add('m', -$reminder->getMinutesBefore());
         }
         $copy_reminder->setDate($reminder_date);
         $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
         $copy_reminder->setObject($new_task);
         $copy_reminder->setType($reminder->getType());
         $copy_reminder->setUserId($reminder->getUserId());
         $copy_reminder->save();
     }
     return $new_task;
 }
	function list_all() {
		ajx_current("empty");
		
		$context = active_context() ;
			
		$start = array_var($_GET, 'start', 0);
		$limit = array_var($_GET, 'limit', config_option('files_per_page'));
		
		$order = array_var($_GET, 'sort');
		if ($order == "updatedOn" || $order == "updated" || $order == "date" || $order == "dateUpdated") $order = "updated_on";
		
		$order_dir = array_var($_GET, 'dir');
		$page = (integer) ($start / $limit) + 1;
		$hide_private = !logged_user()->isMemberOfOwnerCompany();

		if (array_var($_GET,'action') == 'delete') {
			$ids = explode(',', array_var($_GET, 'webpages'));
			$succ = 0; $err = 0;
			foreach ($ids as $id) {
				$web_page = ProjectWebpages::findById($id);
				if (isset($web_page) && $web_page->canDelete(logged_user())) {
					try{
						DB::beginWork();
						$web_page->trash();
						ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_TRASH);
						DB::commit();
						$succ++;
					} catch(Exception $e){
						DB::rollback();
						$err++;
					}
				} else {
					$err++;
				}
			}
			if ($succ > 0) {
				flash_success(lang("success delete objects", $succ));
			}
			if ($err > 0) {
				flash_error(lang("error delete objects", $err));
			}
		}  else if (array_var($_GET, 'action') == 'markasread') {
			$ids = explode(',', array_var($_GET, 'ids'));
			$succ = 0; $err = 0;
				foreach ($ids as $id) {
				$webpage = ProjectWebpages::findById($id);
					try {
						$webpage->setIsRead(logged_user()->getId(),true);
						$succ++;
						
					} catch(Exception $e) {						
						$err ++;
					}
				}
			if ($succ <= 0) {
				flash_error(lang("error markasread files", $err));
			}
		} else if (array_var($_GET, 'action') == 'markasunread') {
			$ids = explode(',', array_var($_GET, 'ids'));
			$succ = 0; $err = 0;
				foreach ($ids as $id) {
				$webpage = ProjectWebpages::findById($id);
					try {
						$webpage->setIsRead(logged_user()->getId(),false);
						$succ++;
						
					} catch(Exception $e) {						
						$err ++;
					}
				}
			if ($succ <= 0) {
				flash_error(lang("error markasunread files", $err));
			}
		} else if (array_var($_GET,'action') == 'archive') {
			$ids = explode(',', array_var($_GET, 'webpages'));
			$succ = 0; $err = 0;
			foreach ($ids as $id) {
				$web_page = ProjectWebpages::findById($id);
				if (isset($web_page) && $web_page->canEdit(logged_user())) {
					try{
						DB::beginWork();
						$web_page->archive();
						ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_ARCHIVE);
						DB::commit();
						$succ++;
					} catch(Exception $e){
						DB::rollback();
						$err++;
					}
				} else {
					$err++;
				}
			}
			if ($succ > 0) {
				flash_success(lang("success archive objects", $succ));
			}
			if ($err > 0) {
				flash_error(lang("error archive objects", $err));
			}
		}
		
		$res =  ProjectWebpages::instance()->listing(array(
			"order" => $order , 
			"order_dir" => $order_dir  
		));
		
		$object = array(
			"totalCount" => $res->total,
			"start" => $start,
			"webpages" => array()
		);
		$custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectWebpages::instance()->getObjectTypeId());
		if (isset($res->objects)) {
			$index = 0;
			$ids = array();
			foreach ($res->objects as $w) {
				$ids[] = $w->getId();
				$object["webpages"][$index] = array(
					"ix" => $index,
					"id" => $w->getId(),
					"object_id" => $w->getObjectId(),
					"ot_id" => $w->getObjectTypeId(),
					"name" => $w->getObjectName(),
					"description" => $w->getDescription(),
					"url" => $w->getUrl(),
					"updatedOn" => $w->getUpdatedOn() instanceof DateTimeValue ? ($w->getUpdatedOn()->isToday() ? format_time($w->getUpdatedOn()) : format_datetime($w->getUpdatedOn())) : '',
					"updatedOn_today" => $w->getUpdatedOn() instanceof DateTimeValue ? $w->getUpdatedOn()->isToday() : 0,
					"updatedBy" => $w->getUpdatedByDisplayName(),
					"updatedById" => $w->getUpdatedById(),
					"memPath" => json_encode($w->getMembersToDisplayPath()),
				);
				
				foreach ($custom_properties as $cp) {
					$cp_value = CustomPropertyValues::getCustomPropertyValue($w->getId(), $cp->getId());
					$object["webpages"][$index]['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : '';
				}
				$index++;
			}
			
			$read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
			foreach($object["webpages"] as &$data) {
				$data['isRead'] = isset($read_objects[$data['object_id']]);
			}
		}
		ajx_extra_data($object);
	}
	/**
	 * Prepares return object for a list of emails and messages
	 *
	 * @param array $totMsg
	 * @param integer $start
	 * @param integer $limit
	 * @return array
	 */
	private function prepareObject($objects, $count, $start = 0, $attributes = null)
	{
		$object = array(
			"totalCount" => $count,
			"start" => $start,
			"contacts" => array()
		);
		$custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(Contacts::instance()->getObjectTypeId());
		for ($i = 0; $i < count($objects); $i++){
			if (isset($objects[$i])){
				$c= $objects[$i];
					
				if ($c instanceof Contact && !$c->isCompany()){						
					$company = $c->getCompany();
					$companyName = '';
					if (!is_null($company))
						$companyName= $company->getObjectName();
					
					$personal_emails = $c->getContactEmails('personal');	
					$w_address = $c->getAddress('work');
					$h_address = $c->getAddress('home');
									
					$object["contacts"][$i] = array(
						"id" => $i,
						"ix" => $i,
						"object_id" => $c->getId(),
						"ot_id" => $c->getObjectTypeId(),
						"type" => 'contact',
						"name" => $c->getReverseDisplayName(),
						"email" => $c->getEmailAddress('personal',true),
						"companyId" => $c->getCompanyId(),
						"companyName" => $companyName,
						"website" => $c->getWebpage('personal') ? cleanUrl($c->getWebpageUrl('personal'), false) : '',
						"jobTitle" => $c->getJobTitle(),
						"department" => $c->getDepartment(),
						"email2" => !is_null($personal_emails) && isset($personal_emails[0]) ? $personal_emails[0]->getEmailAddress() : '',
						"email3" => !is_null($personal_emails) && isset($personal_emails[1]) ? $personal_emails[1]->getEmailAddress() : '',
						"workWebsite" => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '',
						"workAddress" => $w_address ? $c->getFullAddress($w_address) : '',
						"workPhone1" => $c->getPhone('work',true) ? $c->getPhoneNumber('work',true) : '',
						"workPhone2" => $c->getPhone('work') ? $c->getPhoneNumber('work') : '',
						"homeWebsite" => $c->getWebpage('personal') ? cleanUrl($c->getWebpageUrl('personal'), false) : '',
						"homeAddress" => $h_address ? $c->getFullAddress($h_address) : '',
						"homePhone1" => $c->getPhone('home',true) ? $c->getPhoneNumber('home',true) : '',
						"homePhone2" => $c->getPhone('home') ? $c->getPhoneNumber('home') : '',
						"mobilePhone" =>$c->getPhone('mobile') ? $c->getPhoneNumber('mobile') : '',
						"createdOn" => $c->getCreatedOn() instanceof DateTimeValue ? ($c->getCreatedOn()->isToday() ? format_time($c->getCreatedOn()) : format_datetime($c->getCreatedOn())) : '',
						"createdOn_today" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() : 0,
						"createdBy" => $c->getCreatedByDisplayName(),
						"createdById" => $c->getCreatedById(),
						"updatedOn" => $c->getUpdatedOn() instanceof DateTimeValue ? ($c->getUpdatedOn()->isToday() ? format_time($c->getUpdatedOn()) : format_datetime($c->getUpdatedOn())) : '',
						"updatedOn_today" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() : 0,
						"updatedBy" => $c->getUpdatedByDisplayName(),
						"updatedById" => $c->getUpdatedById(),
						"memPath" => json_encode($c->getMembersToDisplayPath()),
						"userType" => $c->getUserType(),
					);
				} else if ($c instanceof Contact){
					
					$w_address = $c->getAddress('work');
					$object["contacts"][$i] = array(
						"id" => $i,
						"ix" => $i,
						"object_id" => $c->getId(),
						"ot_id" => $c->getObjectTypeId(),
						"type" => 'company',
						'name' => $c->getObjectName(),
						'email' => $c->getEmailAddress(),
						'website' => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '',
						'workPhone1' => $c->getPhone('work',true) ? $c->getPhoneNumber('work',true) : '',
                        'workPhone2' => $c->getPhone('fax',true) ? $c->getPhoneNumber('fax',true) : '',
                        'workAddress' => $w_address ? $c->getFullAddress($w_address) : '',
						"companyId" => $c->getId(),
						"companyName" => $c->getObjectName(),
						"jobTitle" => '',
                        "department" => lang('company'),
						"email2" => '',
						"email3" => '',
						"workWebsite" => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '',
						"homeWebsite" => '',
						"homeAddress" => '',
						"homePhone1" => '',
						"homePhone2" => '',
						"mobilePhone" =>'',
						"createdOn" => $c->getCreatedOn() instanceof DateTimeValue ? ($c->getCreatedOn()->isToday() ? format_time($c->getCreatedOn()) : format_datetime($c->getCreatedOn())) : '',
						"createdOn_today" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() : 0,
						"createdBy" => $c->getCreatedByDisplayName(),
						"createdById" => $c->getCreatedById(),
						"updatedOn" => $c->getUpdatedOn() instanceof DateTimeValue ? ($c->getUpdatedOn()->isToday() ? format_time($c->getUpdatedOn()) : format_datetime($c->getUpdatedOn())) : '',
						"updatedOn_today" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() : 0,
						"updatedBy" => $c->getUpdatedByDisplayName(),
						"updatedById" => $c->getUpdatedById(),
						"memPath" => json_encode($c->getMembersToDisplayPath()),
						"contacts" => $c->getContactsByCompany(),
						"users" => $c->getUsersByCompany(),
					);
				}
				
				foreach ($custom_properties as $cp) {
					$cp_value = CustomPropertyValues::getCustomPropertyValue($c->getId(), $cp->getId());
					$object["contacts"][$i]['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : '';
				}
    		}
		}
		return $object;
	}
 /**
 * Return manager instance
 *
 * @access protected
 * @param void
 * @return CustomPropertyValue 
 */
 function manager() {
   if(!($this->manager instanceof CustomPropertyValues )) $this->manager =  CustomPropertyValues::instance();
   return $this->manager;
 } // manager
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return CustomPropertyValue 
  */
 function manager()
 {
     if (!$this->manager instanceof CustomPropertyValues) {
         $this->manager = CustomPropertyValues::instance();
     }
     return $this->manager;
 }
 /**
  * This method will run query in og_custom_properties table and
  * fetch user phone number where it is available
  * Added By aqureshi
  */
 function getPhoneNumberCustomProperty($user_idss)
 {
     $cstm_users_table = CustomPropertyValues::instance()->getTableName(true);
     $sql = "SELECT id, object_id,custom_property_id , `value`  FROM {$cstm_users_table} WHERE (`object_id` in ( {$user_idss} ) ) ";
     $rows = DB::executeAll($sql);
     if (is_array($rows)) {
         foreach ($rows as $row) {
             return $row['value'];
         }
         // foreach
     }
     // if
 }
	/**
	 * Prepares return object for a list of emails and messages
	 *
	 * @param array $totMsg
	 * @param integer $start
	 * @param integer $limit
	 * @return array
	 */
	private function prepareObject($emails, $start, $limit, $total, $attributes = null) {
		$object = array(
			"totalCount" => intval($total),
			"start" => $start,//(integer)min(array(count($totMsg) - (count($totMsg) % $limit),$start)),
			"messages" => array()
		);
		$custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(MailContents::instance()->getObjectTypeId());
		$i=0;
		foreach ($emails as $email) {
			if ($email instanceof MailContent) {
				$properties = $this->getMailProperties($email, $i);
				$object["messages"][$i] = $properties;
			}
			foreach ($custom_properties as $cp) {
				$cp_value = CustomPropertyValues::getCustomPropertyValue($email->getId(), $cp->getId());
				$object["messages"][$i]['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : '';
			}
			$i++;
		}
		return $object;
	}
 function copy_custom_properties($object_from)
 {
     if (!$object_from instanceof ContentDataObject) {
         return;
     }
     $cp_values = CustomPropertyValues::findAll(array('conditions' => 'object_id = ' . $object_from->getId()));
     foreach ($cp_values as $cp_value) {
         $new_cp_value = new CustomPropertyValue();
         $new_cp_value->setObjectId($this->getId());
         $new_cp_value->setCustomPropertyId($cp_value->getCustomPropertyId());
         $new_cp_value->setValue($cp_value->getValue());
         $new_cp_value->save();
     }
 }
 /**
  * Adds the custom properties of an object into the database.
  * 
  * @param $object
  * @return unknown_type
  */
 function add_custom_properties($object)
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $obj_custom_properties = array_var($_POST, 'object_custom_properties');
     if (is_array($obj_custom_properties)) {
         foreach ($obj_custom_properties as $id => &$val) {
             $val = remove_scripts($val);
         }
     }
     $date_format = user_config_option('date_format');
     $date_format_tip = date_format_tip($date_format);
     $required_custom_props = array();
     $object_type_id = $object instanceof TemplateTask ? ProjectTasks::instance()->getObjectTypeId() : $object->getObjectTypeId();
     $customProps = CustomProperties::getAllCustomPropertiesByObjectType($object_type_id);
     //Sets all boolean custom properties to 0. If any boolean properties are returned, they are subsequently set to 1.
     foreach ($customProps as $cp) {
         if ($cp->getType() == 'boolean') {
             $custom_property_value = CustomPropertyValues::getCustomPropertyValue($object->getId(), $cp->getId());
             if (!$custom_property_value instanceof CustomPropertyValue) {
                 $custom_property_value = new CustomPropertyValue();
             }
             $custom_property_value->setObjectId($object->getId());
             $custom_property_value->setCustomPropertyId($cp->getId());
             $custom_property_value->setValue(0);
             $custom_property_value->save();
         }
         if ($cp->getIsRequired()) {
             $required_custom_props[] = $cp;
         }
     }
     foreach ($required_custom_props as $req_cp) {
         if (!isset($obj_custom_properties[$req_cp->getId()])) {
             throw new Exception(lang('custom property value required', $req_cp->getName()));
         }
     }
     if (is_array($obj_custom_properties)) {
         // check required custom properties
         foreach ($obj_custom_properties as $id => $value) {
             //Get the custom property
             $custom_property = null;
             foreach ($customProps as $cp) {
                 if ($cp->getId() == $id) {
                     $custom_property = $cp;
                     break;
                 }
             }
             if ($custom_property instanceof CustomProperty) {
                 // save dates in standard format "Y-m-d H:i:s", because the column type is string
                 if ($custom_property->getType() == 'date') {
                     if (is_array($value)) {
                         $newValues = array();
                         foreach ($value as $val) {
                             if (trim($val) != '' && trim($val) != $date_format_tip) {
                                 $dtv = DateTimeValueLib::dateFromFormatAndString($date_format, $val);
                                 $newValues[] = $dtv->format("Y-m-d H:i:s");
                             }
                         }
                         $value = $newValues;
                     } else {
                         if (trim($value) != '' && trim($val) != $date_format_tip) {
                             $dtv = DateTimeValueLib::dateFromFormatAndString($date_format, $value);
                             $value = $dtv->format("Y-m-d H:i:s");
                         } else {
                             $value = '';
                         }
                     }
                 }
                 foreach (array_var($_REQUEST, 'remove_custom_properties', array()) as $cpropid => $remove) {
                     if ($remove) {
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $cpropid);
                     }
                 }
                 Hook::fire('before_save_custom_property_value', array('custom_prop' => $custom_property), $value);
                 if (is_array($value)) {
                     if ($custom_property->getType() == 'address') {
                         if ($custom_property->getIsRequired()) {
                             if (array_var($value, 'street') == '' && array_var($value, 'city') == '' && array_var($value, 'state') == '' && array_var($value, 'country') == '' && array_var($value, 'zip_code') == '') {
                                 throw new Exception(lang('custom property value required', $custom_property->getName()));
                             }
                             $errors = array(lang('error form validation'));
                             Env::useHelper('form');
                             $ok = checkAddressInputMandatoryFields($value, $custom_property->getName(), $errors);
                             if (!$ok) {
                                 throw new Exception(implode("\n - ", $errors));
                             }
                         }
                         // Address custom property
                         $val = array_var($value, 'type') . '|' . array_var($value, 'street') . '|' . array_var($value, 'city') . '|' . array_var($value, 'state') . '|' . array_var($value, 'country') . '|' . array_var($value, 'zip_code');
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $id);
                         $custom_property_value = new CustomPropertyValue();
                         $custom_property_value->setObjectId($object->getId());
                         $custom_property_value->setCustomPropertyId($id);
                         $custom_property_value->setValue($val);
                         $custom_property_value->save();
                     } else {
                         //Save multiple values
                         CustomPropertyValues::deleteCustomPropertyValues($object->getId(), $id);
                         foreach ($value as &$val) {
                             if (is_array($val)) {
                                 // CP type == table
                                 $str_val = '';
                                 foreach ($val as $col_val) {
                                     $col_val = str_replace("|", "\\|", $col_val);
                                     $str_val .= ($str_val == '' ? '' : '|') . $col_val;
                                 }
                                 $val = $str_val;
                             }
                             if ($val != '') {
                                 $custom_property_value = new CustomPropertyValue();
                                 $custom_property_value->setObjectId($object->getId());
                                 $custom_property_value->setCustomPropertyId($id);
                                 $custom_property_value->setValue($val);
                                 $custom_property_value->save();
                             }
                         }
                     }
                 } else {
                     if ($custom_property->getType() == 'boolean') {
                         $value = isset($value);
                     }
                     $cpv = CustomPropertyValues::getCustomPropertyValue($object->getId(), $id);
                     if ($cpv instanceof CustomPropertyValue) {
                         $custom_property_value = $cpv;
                     } else {
                         $custom_property_value = new CustomPropertyValue();
                         $custom_property_value->setObjectId($object->getId());
                         $custom_property_value->setCustomPropertyId($id);
                     }
                     $custom_property_value->setValue($value);
                     $custom_property_value->save();
                 }
                 //Add to searchable objects
                 if ($object->isSearchable() && ($custom_property->getType() == 'text' || $custom_property->getType() == 'list' || $custom_property->getType() == 'numeric')) {
                     $name = str_replace("'", "\\'", $custom_property->getName());
                     if (is_array($value)) {
                         $value = implode(', ', $value);
                     }
                     $value = str_replace("'", "\\'", $value);
                     $sql = "INSERT INTO " . TABLE_PREFIX . "searchable_objects (rel_object_id, column_name, content)\r\n\t\t\t\t\t\tVALUES ('" . $object->getId() . "', '" . $name . "', '" . $value . "')\r\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE content='" . $value . "'";
                     DB::execute($sql);
                 }
             }
         }
     }
     //Save the key - value pair custom properties (object_properties table)
     $object->clearObjectProperties();
     $names = array_var($_POST, 'custom_prop_names');
     $values = array_var($_POST, 'custom_prop_values');
     if (!is_array($names)) {
         return;
     }
     for ($i = 0; $i < count($names); $i++) {
         $name = trim($names[$i]);
         $value = trim($values[$i]);
         if ($name != '' && $value != '') {
             $property = new ObjectProperty();
             $property->setObject($object);
             $property->setPropertyName($name);
             $property->setPropertyValue($value);
             $property->save();
             if ($object->isSearchable()) {
                 $object->addPropertyToSearchableObject($property);
             }
         }
     }
 }
	/**
	 * Prepares return object for a list of emails and messages
	 *
	 * @param array $totMsg
	 * @param integer $start
	 * @param integer $limit
	 * @return array
	 */
	private function prepareObject($totMsg, $start, $limit, $total) {
		$object = array(
			"totalCount" => $total,
			"start" => $start,
			"messages" => array()
		);
		$custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectMessages::instance()->getObjectTypeId());
		$ids = array();
		for ($i = 0; $i < $limit; $i++){
			if (isset($totMsg[$i])){
				$msg = $totMsg[$i];
				if ($msg instanceof ProjectMessage){
					$text = $msg->getText();
					if (strlen($text) > 100) $text = substr_utf($text,0,100) . "...";
					$object["messages"][$i] = array(
					    "id" => $i,
						"ix" => $i,
						"object_id" => $msg->getId(),
						"ot_id" => $msg->getObjectTypeId(),
						"type" => $msg->getObjectTypeName(),
						"name" => $msg->getObjectName(),
						"text" => html_to_text($text),
						"date" => $msg->getUpdatedOn() instanceof DateTimeValue ? ($msg->getUpdatedOn()->isToday() ? format_time($msg->getUpdatedOn()) : format_datetime($msg->getUpdatedOn())) : '',
						"is_today" => $msg->getUpdatedOn() instanceof DateTimeValue ? $msg->getUpdatedOn()->isToday() : 0,
						"userId" => $msg->getCreatedById(),
						"userName" => $msg->getCreatedByDisplayName(),
						"updaterId" => $msg->getUpdatedById() ? $msg->getUpdatedById() : $msg->getCreatedById(),
						"updaterName" => $msg->getUpdatedById() ? $msg->getUpdatedByDisplayName() : $msg->getCreatedByDisplayName(),
						"memPath" => json_encode($msg->getMembersToDisplayPath()),
					);
					$ids[] = $msg->getId();
					
					foreach ($custom_properties as $cp) {
						$cp_value = CustomPropertyValues::getCustomPropertyValue($msg->getId(), $cp->getId());
						$object["messages"][$i]['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : '';
					}
    			}
			}
		}
		
		$read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
		foreach($object["messages"] as &$data) {
			$data['isRead'] = isset($read_objects[$data['object_id']]);
		}
		
		return $object;
	}
Exemple #14
0
/**
 * Copies related data from an object to another (members, linked_objects, custom_properties, subscribers, reminders and comments)
 * @param $object: Original object to copy data
 * @param $copy: Object to be modified with the data of the $orignal object
 * @param $options: set which type of data will not be copied
 */
function copy_additional_object_data($object, &$copy, $options = array())
{
    if (!$object instanceof ContentDataObject || !$copy instanceof ContentDataObject) {
        // if not valid objects return
        return;
    }
    $copy_members = !array_var($options, 'dont_copy_members');
    $copy_linked_objects = !array_var($options, 'dont_copy_linked_objects');
    $copy_custom_properties = !array_var($options, 'dont_copy_custom_properties');
    $copy_subscribers = !array_var($options, 'dont_copy_subscribers');
    $copy_reminders = !array_var($options, 'dont_copy_reminders');
    $copy_comments = !array_var($options, 'dont_copy_comments');
    $controller = new ObjectController();
    // copy members
    if ($copy_members) {
        $object_members = $object->getMembers();
        $copy->addToMembers($object_members);
        Hook::fire('after_add_to_members', $copy, $object_members);
        $copy->addToSharingTable();
    }
    // copy linked objects
    if ($copy_linked_objects) {
        $copy->copyLinkedObjectsFrom($object);
    }
    // copy custom properties
    if ($copy_custom_properties) {
        // custom properties defined in "settings"
        $cp_object_type_id = $object->getObjectTypeId();
        if ($object instanceof TemplateTask || $object instanceof TemplateMilestone) {
            $cp_object_type_id = $copy->getObjectTypeId();
        }
        $custom_props = CustomProperties::getAllCustomPropertiesByObjectType($cp_object_type_id);
        foreach ($custom_props as $c_prop) {
            $values = CustomPropertyValues::getCustomPropertyValues($object->getId(), $c_prop->getId());
            if (is_array($values)) {
                foreach ($values as $val) {
                    $cp = new CustomPropertyValue();
                    $cp->setObjectId($copy->getId());
                    $cp->setCustomPropertyId($val->getCustomPropertyId());
                    $cp->setValue($val->getValue());
                    $cp->save();
                }
            }
        }
        // object properties (key-value)
        $copy->copyCustomPropertiesFrom($object);
    }
    // copy subscribers
    if ($copy_subscribers) {
        $subscribers_array = array();
        foreach ($object->getSubscriberIds() as $user_id) {
            $subscribers_array["user_" . $user_id] = "1";
        }
        $controller->add_subscribers($copy, $subscribers_array);
    }
    // copy reminders
    if ($copy_reminders) {
        $reminders = ObjectReminders::getByObject($object);
        foreach ($reminders as $reminder) {
            $copy_reminder = new ObjectReminder();
            $copy_reminder->setContext($reminder->getContext());
            $reminder_date = $copy->getColumnValue($reminder->getContext());
            if ($reminder_date instanceof DateTimeValue) {
                $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
                $reminder_date->add('m', -$reminder->getMinutesBefore());
            }
            $copy_reminder->setDate($reminder_date);
            $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
            $copy_reminder->setObject($copy);
            $copy_reminder->setType($reminder->getType());
            $copy_reminder->setUserId($reminder->getUserId());
            $copy_reminder->save();
        }
    }
    // copy comments
    if ($copy_comments) {
        foreach ($object->getAllComments() as $com) {
            $new_com = new Comment();
            $new_com->setAuthorEmail($com->getAuthorEmail());
            $new_com->setAuthorName($com->getAuthorName());
            $new_com->setAuthorHomepage($com->getAuthorHomepage());
            $new_com->setCreatedById($com->getCreatedById());
            $new_com->setCreatedOn($com->getCreatedOn());
            $new_com->setUpdatedById($com->getUpdatedById());
            $new_com->setUpdatedOn($com->getUpdatedOn());
            $new_com->setText($com->getText());
            $new_com->setRelObjectId($copy->getId());
            $new_com->save();
        }
    }
}
         $name .= '[]';
         echo select_box($name, $options, array('tabindex' => $startTi + $ti, 'style' => 'min-width:140px', 'size' => $totalOptions, 'multiple' => 'multiple', 'id' => $genid . 'cp' . $customProp->getId()));
     } else {
         echo select_box($name, $options, array('tabindex' => $startTi + $ti, 'style' => 'min-width:140px', 'id' => $genid . 'cp' . $customProp->getId()));
     }
     break;
 case 'table':
     $columnNames = explode(',', $customProp->getValues());
     $cell_width = 600 / count($columnNames) . "px";
     $html = '<div class="og-add-custom-properties"><table><tr>';
     foreach ($columnNames as $colName) {
         $html .= '<th style="width:' . $cell_width . ';min-width:120px;">' . $colName . '</th>';
     }
     $ti += 1000;
     $html .= '</tr><tr>';
     $values = CustomPropertyValues::getCustomPropertyValues($_custom_properties_object->getId(), $customProp->getId());
     if (!is_array($values) || count($values) == 0) {
         $def_cp_value = new CustomPropertyValue();
         $def_cp_value->setValue($default_value);
         $values = array($def_cp_value);
     }
     $rows = 0;
     if (is_array($values) && count($values) > 0) {
         foreach ($values as $val) {
             $col = 0;
             $values = str_replace("\\|", "%%_PIPE_%%", $val->getValue());
             $exploded = explode("|", $values);
             foreach ($exploded as $v) {
                 $v = str_replace("%%_PIPE_%%", "|", $v);
                 $html .= '<td><input class="value" style="width:' . $cell_width . ';min-width:120px;" name="' . $name . "[{$rows}][{$col}]" . '" value="' . clean($v) . '" tabindex="' . ($startTi + $ti++) . '"/></td>';
                 $col++;
Exemple #16
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
 function total_task_times_csv($report_data, $columns, $timeslotsArray, $skip_ws = false)
 {
     //$types = self::get_report_column_types($report->getId());
     $filename = str_replace(' ', '_', lang('task time report')) . date('_YmdHis');
     header('Expires: 0');
     header('Cache-control: private');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Content-Description: File Transfer');
     header('Content-Type: application/csv');
     header('Content-disposition: attachment; filename=' . $filename . '.csv');
     // titles
     $titles = lang('date') . ";" . lang('title') . ";" . lang('description') . ";" . lang('user') . ";" . lang('time') . ";";
     if (array_var($report_data, 'show_billing', false)) {
         $titles .= lang('billing') . ";";
     }
     foreach ($columns as $id => $pos) {
         if ($pos == 0) {
             continue;
         }
         if (!is_numeric($id)) {
             $col_name = lang("field ProjectTasks " . $id);
         } else {
             $cp = CustomProperties::getCustomProperty($id);
             $col_name = $cp->getName();
         }
         $titles .= $col_name . ";";
     }
     $titles = iconv(mb_internal_encoding(), "ISO-8859-1", html_entity_decode($titles, ENT_COMPAT));
     echo "{$titles}\n";
     // data
     foreach ($timeslotsArray as $tsRow) {
         $ts = $tsRow["ts"];
         if ($skip_ws && $ts->getObjectManager() == 'Projects') {
             continue;
         }
         $to_print = format_date($ts->getStartTime()) . ";";
         if ($ts->getObject() instanceof ProjectTask) {
             $to_print .= $ts->getObject()->getTitle() . ";";
             $to_print .= $ts->getObject()->getText() . ";";
         } else {
             if ($ts->getObject() instanceof Project) {
                 $ws_name = lang('workspace') . ' ' . clean($ts->getObject()->getName());
                 $to_print .= "{$ws_name};;";
             } else {
                 $to_print .= ";;";
             }
         }
         $to_print .= clean(Users::getUserDisplayName($ts->getUserId())) . ";";
         $lastStop = $ts->getEndTime() != null ? $ts->getEndTime() : ($ts->isPaused() ? $ts->getPausedOn() : DateTimeValueLib::now()) . ";";
         $to_print .= DateTimeValue::FormatTimeDiff($ts->getStartTime(), $lastStop, "hm", 60, $ts->getSubtract()) . ";";
         if (array_var($report_data, 'show_billing', false)) {
             $to_print .= config_option('currency_code', '$') . " " . $ts->getFixedBilling();
         }
         // other columns
         foreach ($columns as $id => $pos) {
             if ($pos == 0) {
                 continue;
             }
             if ($ts->getObject() instanceof ProjectTask) {
                 if (!is_numeric($id)) {
                     $col_value = self::format_value_to_print($id, $ts->getObject()->getColumnValue($id), $ts->getObject()->manager()->getColumnType($id), $ts->getObject()->getObjectManagerName());
                 } else {
                     $cp = CustomProperties::getCustomProperty($id);
                     $cpv = CustomPropertyValues::getCustomPropertyValue($ts->getObject()->getId(), $cp->getId());
                     if ($cpv instanceof CustomPropertyValue) {
                         $col_value = self::format_value_to_print($cp->getName(), $cpv->getValue(), $cp->getOgType(), $ts->getObject()->getObjectManagerName());
                     } else {
                         $col_value = "";
                     }
                 }
             } else {
                 $col_value = "";
             }
             $to_print .= $col_value . ";";
         }
         $to_print = iconv(mb_internal_encoding(), "ISO-8859-1", html_entity_decode($to_print, ENT_COMPAT));
         echo "{$to_print}\n";
     }
     die;
 }
 /**
  * This function will return paginated result. Result is an array where first element is 
  * array of returned object and second populated pagination object that can be used for 
  * obtaining and rendering pagination data using various helpers.
  * 
  * Items and pagination array vars are indexed with 0 for items and 1 for pagination
  * because you can't use associative indexing with list() construct
  *
  * @access public
  * @param array $arguments Query argumens (@see find()) Limit and offset are ignored!
  * @param integer $items_per_page Number of items per page
  * @param integer $current_page Current page number
  * @return array
  */
 function paginate($arguments = null, $items_per_page = 10, $current_page = 1)
 {
     if (isset($this) && instance_of($this, 'CustomPropertyValues')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return CustomPropertyValues::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
Exemple #19
0
function get_custom_property_value_for_listing($cp, $obj)
{
    $cp_vals = CustomPropertyValues::getCustomPropertyValues($obj->getId(), $cp->getId());
    $val_to_show = "";
    foreach ($cp_vals as $cp_val) {
        if (in_array($cp->getType(), array('contact', 'user')) && $cp_val instanceof CustomPropertyValue) {
            $cp_contact = Contacts::findById($cp_val->getValue());
            if ($cp_contact instanceof Contact) {
                $cp_val->setValue($cp_contact->getObjectName());
            } else {
                $cp_val->setValue("");
            }
        }
        if ($cp->getType() == 'date' && $cp_val instanceof CustomPropertyValue) {
            $format = user_config_option('date_format');
            Hook::fire("custom_property_date_format", null, $format);
            $tmp_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $cp_val->getValue());
            if (str_starts_with($cp_val->getValue(), EMPTY_DATE)) {
                $formatted = "";
            } else {
                if (str_ends_with($cp_val->getValue(), "00:00:00")) {
                    $formatted = $tmp_date->format(user_config_option('date_format'));
                } else {
                    $formatted = $tmp_date->format($format);
                }
            }
            $cp_val->setValue($formatted);
        }
        if ($cp->getType() == 'address' && $cp_val instanceof CustomPropertyValue) {
            $values = str_replace("\\|", "%%_PIPE_%%", $cp_val->getValue());
            $exploded = explode("|", $values);
            foreach ($exploded as &$v) {
                $v = str_replace("%%_PIPE_%%", "|", $v);
                $v = escape_character($v);
            }
            if (count($exploded) > 0) {
                $address_type = array_var($exploded, 0, '');
                $street = array_var($exploded, 1, '');
                $city = array_var($exploded, 2, '');
                $state = array_var($exploded, 3, '');
                $country = array_var($exploded, 4, '');
                $zip_code = array_var($exploded, 5, '');
                $country_name = CountryCodes::getCountryNameByCode($country);
                $tmp = array();
                if ($street != '') {
                    $tmp[] = $street;
                }
                if ($city != '') {
                    $tmp[] = $city;
                }
                if ($state != '') {
                    $tmp[] = $state;
                }
                if ($zip_code != '') {
                    $tmp[] = $zip_code;
                }
                if ($country_name != '') {
                    $tmp[] = $country_name;
                }
                $cp_val->setValue(implode(' - ', $tmp));
            }
        }
        $val_to_show .= ($val_to_show == "" ? "" : ", ") . ($cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : "");
    }
    return $val_to_show;
}
 function cloneTask($copy_status = false)
 {
     $new_task = new ProjectTask();
     $new_task->setParentId($this->getParentId());
     $new_task->setTitle($this->getTitle());
     $new_task->setText($this->getText());
     $new_task->setAssignedToCompanyId($this->getAssignedToCompanyId());
     $new_task->setAssignedToUserId($this->getAssignedToUserId());
     $new_task->setAssignedOn($this->getAssignedOn());
     $new_task->setAssignedById($this->getAssignedById());
     $new_task->setTimeEstimate($this->getTimeEstimate());
     $new_task->setStartedOn($this->getStartedOn());
     $new_task->setStartedById($this->getStartedById());
     $new_task->setPriority($this->getPriority());
     $new_task->setState($this->getState());
     $new_task->setOrder($this->getOrder());
     $new_task->setMilestoneId($this->getMilestoneId());
     $new_task->setIsPrivate($this->getIsPrivate());
     $new_task->setIsTemplate($this->getIsTemplate());
     $new_task->setFromTemplateId($this->getFromTemplateId());
     if ($this->getDueDate() instanceof DateTimeValue) {
         $new_task->setDueDate(new DateTimeValue($this->getDueDate()->getTimestamp()));
     }
     if ($this->getStartDate() instanceof DateTimeValue) {
         $new_task->setStartDate(new DateTimeValue($this->getStartDate()->getTimestamp()));
     }
     if ($copy_status) {
         $new_task->setCompletedById($this->getCompletedById());
         $new_task->setCompletedOn($this->getCompletedOn());
     }
     $new_task->save();
     $new_task->setTagsFromCSV(implode(",", $this->getTagNames()));
     foreach ($this->getWorkspaces() as $ws) {
         $new_task->addToWorkspace($ws);
     }
     if (is_array($this->getAllLinkedObjects())) {
         foreach ($this->getAllLinkedObjects() as $lo) {
             $new_task->linkObject($lo);
         }
     }
     $sub_tasks = $this->getAllSubTasks();
     foreach ($sub_tasks as $st) {
         if ($st->getParentId() == $this->getId()) {
             $new_st = $st->cloneTask($copy_status);
             if ($copy_status) {
                 $new_st->setCompletedById($st->getCompletedById());
                 $new_st->setCompletedOn($st->getCompletedOn());
                 $new_st->save();
             }
             $new_task->attachTask($new_st);
         }
     }
     foreach ($this->getAllComments() as $com) {
         $new_com = new Comment();
         $new_com->setAuthorEmail($com->getAuthorEmail());
         $new_com->setAuthorName($com->getAuthorName());
         $new_com->setAuthorHomepage($com->getAuthorHomepage());
         $new_com->setCreatedById($com->getCreatedById());
         $new_com->setCreatedOn($com->getCreatedOn());
         $new_com->setUpdatedById($com->getUpdatedById());
         $new_com->setUpdatedOn($com->getUpdatedOn());
         $new_com->setIsAnonymous($com->getIsAnonymous());
         $new_com->setIsPrivate($com->getIsPrivate());
         $new_com->setText($com->getText());
         $new_com->setRelObjectId($new_task->getId());
         $new_com->setRelObjectManager("ProjectTasks");
         $new_com->save();
     }
     $_POST['subscribers'] = array();
     foreach ($this->getSubscribers() as $sub) {
         $_POST['subscribers']["user_" . $sub->getId()] = "checked";
     }
     $obj_controller = new ObjectController();
     $obj_controller->add_subscribers($new_task);
     foreach ($this->getCustomProperties() as $prop) {
         $new_prop = new ObjectProperty();
         $new_prop->setRelObjectId($new_task->getId());
         $new_prop->setRelObjectManager($prop->getRelObjectManager());
         $new_prop->setPropertyName($prop->getPropertyName());
         $new_prop->setPropertyValue($prop->getPropertyValue());
         $new_prop->save();
     }
     $custom_props = CustomProperties::getAllCustomPropertiesByObjectType("ProjectTasks");
     foreach ($custom_props as $c_prop) {
         $values = CustomPropertyValues::getCustomPropertyValues($this->getId(), $c_prop->getId());
         if (is_array($values)) {
             foreach ($values as $val) {
                 $cp = new CustomPropertyValue();
                 $cp->setObjectId($new_task->getId());
                 $cp->setCustomPropertyId($val->getCustomPropertyId());
                 $cp->setValue($val->getValue());
                 $cp->save();
             }
         }
     }
     $reminders = ObjectReminders::getByObject($this);
     foreach ($reminders as $reminder) {
         $copy_reminder = new ObjectReminder();
         $copy_reminder->setContext($reminder->getContext());
         $reminder_date = $new_task->getColumnValue($reminder->getContext());
         if ($reminder_date instanceof DateTimeValue) {
             $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
             $reminder_date->add('m', -$reminder->getMinutesBefore());
         }
         $copy_reminder->setDate($reminder_date);
         $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
         $copy_reminder->setObject($new_task);
         $copy_reminder->setType($reminder->getType());
         $copy_reminder->setUserId($reminder->getUserId());
         $copy_reminder->save();
     }
     return $new_task;
 }