/**
  * Return object
  *
  * @param void
  * @return ApplicationDataObject
  */
 function getObject()
 {
     if (is_null($this->object)) {
         $this->object = Objects::findObject($this->getObjectId());
     }
     return $this->object;
 }
 public function rebuild($start_date = null, $end_date = null)
 {
     if (!$start_date) {
         $start_date = config_option('last_sharing_table_rebuild');
     }
     if ($start_date instanceof DateTimeValue) {
         $start_date = $start_date->toMySQL();
     }
     if ($end_date instanceof DateTimeValue) {
         $end_date = $end_date->toMySQL();
     }
     if ($end_date) {
         $end_cond = "AND updated_on <= '{$end_date}'";
     }
     try {
         $object_ids = Objects::instance()->findAll(array('id' => true, "conditions" => "updated_on >= '{$start_date}' {$end_cond}"));
         $obj_count = 0;
         DB::beginWork();
         foreach ($object_ids as $id) {
             $obj = Objects::findObject($id);
             if ($obj instanceof ContentDataObject) {
                 $obj->addToSharingTable();
                 $obj_count++;
             }
         }
         set_config_option('last_sharing_table_rebuild', DateTimeValueLib::now()->toMySQL());
         DB::commit();
     } catch (Exception $e) {
         DB::rollback();
         Logger::log("Failed to rebuild sharing table: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
     }
     return $obj_count;
 }
Exemple #3
0
 function purge_trash()
 {
     Env::useHelper("permissions");
     $days = config_option("days_on_trash", 0);
     $count = 0;
     if ($days > 0) {
         $date = DateTimeValueLib::now()->add("d", -$days);
         $objects = Objects::findAll(array("conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100));
         foreach ($objects as $object) {
             $concrete_object = Objects::findObject($object->getId());
             if (!$concrete_object instanceof ContentDataObject) {
                 continue;
             }
             if ($concrete_object instanceof MailContent && $concrete_object->getIsDeleted() > 0) {
                 continue;
             }
             try {
                 DB::beginWork();
                 if ($concrete_object instanceof MailContent) {
                     $concrete_object->delete(false);
                 } else {
                     $concrete_object->delete();
                 }
                 ApplicationLogs::createLog($concrete_object, ApplicationLogs::ACTION_DELETE);
                 DB::commit();
                 $count++;
             } catch (Exception $e) {
                 DB::rollback();
                 Logger::log("Error delting object in purge_trash: " . $e->getMessage(), Logger::ERROR);
             }
         }
     }
     return $count;
 }
 /**
 * Return object connected with this action, that is not equal to the one received
 *
 * @access public
 * @param  ProjectDataObject $object
 * @return ProjectDataObject
 */
 function getOtherObject($object) {
   if (($object->getObjectId()!= $this->getObjectId()) ) {
   		return Objects::findObject($this->getObjectId());
   } else {
   		return Objects::findObject($this->getRelObjectId());
   }
 } // getObject
function mail_do_mark_as_read_unread_objects($ids_to_mark, $read)
{
    $all_accounts = array();
    $all_accounts_ids = array();
    foreach ($ids_to_mark as $id) {
        $obj = Objects::findObject($id);
        if ($obj instanceof MailContent && logged_user() instanceof Contact) {
            //conversation set the rest of the conversation
            $uds_to_mark_from_conver = array();
            if (user_config_option('show_emails_as_conversations')) {
                $emails_in_conversation = MailContents::getMailsFromConversation($obj);
                foreach ($emails_in_conversation as $email) {
                    //$id is marked on object controller only mark the rest of the conversation
                    if ($id != $email->getId()) {
                        $email->setIsRead(logged_user()->getId(), $read);
                        $uds_to_mark_from_conver[] = $email->getUid();
                    }
                }
            }
            //make the array with accounts and uids to send to the mail server
            //accounts
            if (!in_array($obj->getAccountId(), $all_accounts_ids)) {
                $account = $obj->getAccount();
                //if logged user is owner of this account and is imap
                if ($account instanceof MailAccount && $account->getContactId() == logged_user()->getId() && $account->getIsImap()) {
                    $all_accounts_ids[] = $obj->getAccountId();
                    $all_accounts[$account->getId()]['account'] = $account;
                }
            }
            //uids
            if (in_array($obj->getAccountId(), $all_accounts_ids)) {
                //add conversations uids
                //mientras ande mal el uid de los mails enviados si estan sincronizados no usar esta parte
                /*if (user_config_option('show_emails_as_conversations')) {
                			foreach ($uds_to_mark_from_conver as $uid_conver){
                				$all_accounts[$obj->getAccountId()]['uids'][] = $uid_conver;
                			}
                		}*/
                $all_accounts[$obj->getAccountId()]['folders'][$obj->getImapFolderName()][] = $obj->getUid();
            }
        }
    }
    //foreach account send uids by folder to mark in the mail server
    foreach ($all_accounts as $account_data) {
        $account = $account_data['account'];
        $folders = $account_data['folders'];
        foreach ($folders as $key => $folder) {
            $folder_name = $key;
            $uids = $folder;
            if (!empty($folder_name)) {
                try {
                    MailUtilities::setReadUnreadImapMails($account, $folder_name, $uids, $read);
                } catch (Exception $e) {
                    Logger::log("Could not set mail as read on mail server, exception:\n" . $e->getMessage());
                }
            }
        }
    }
}
	/**
	 * Returns all Objects of a Template
	 *
	 * @param integer $template_id
	 * @return array
	 */
	static function getObjectsByTemplate($template_id) {
		$all = self::findAll(array('conditions' => array('`template_id` = ?', $template_id) ));
		if (!is_array($all)) return array();
		$objs = array();
		foreach ($all as $obj) {
			$objs[] = Objects::findObject($obj->getObjectId());
		
		}
		
		return $objs;
	}
 function healPermissionGroup(SharingTableFlag $flag)
 {
     if ($flag->getObjectId() > 0) {
         try {
             $obj = Objects::findObject($flag->getObjectId());
             if (!$obj instanceof ContentDataObject) {
                 $flag->delete();
                 // if object does not exists then delete the flag
                 return;
             }
             DB::beginWork();
             // update sharing table
             $obj->addToSharingTable();
             DB::commit();
         } catch (Exception $e) {
             DB::rollback();
             Logger::log("Failed to heal object permissions for object " . $flag->getObjectId() . " (flag_id = " . $flag->getId() . ")");
             return false;
         }
         // delete flag
         $flag->delete();
         return true;
     } else {
         // heal
         $controller = new SharingTableController();
         $permissions_string = $flag->getPermissionString();
         $permission_group_id = $flag->getPermissionGroupId();
         $permissions = json_decode($permissions_string);
         if ($flag->getMemberId() > 0) {
             foreach ($permissions as $p) {
                 if (!isset($p->m)) {
                     $p->m = $flag->getMemberId();
                 }
             }
         }
         try {
             DB::beginWork();
             // update sharing table
             $controller->afterPermissionChanged($permission_group_id, $permissions);
             DB::commit();
         } catch (Exception $e) {
             DB::rollback();
             Logger::log("Failed to heal permission group {$permission_group_id} (flag_id = " . $flag->getId() . ")\n" . $e->getTraceAsString());
             return false;
         }
         // delete flag
         $flag->delete();
         return true;
     }
 }
 /**
  * Returns all Objects of a Template
  *
  * @param integer $template_id
  * @return array
  */
 static function getObjectsByTemplate($template_id)
 {
     $all = self::findAll(array('conditions' => array('`template_id` = ?', $template_id)));
     if (!is_array($all)) {
         return array();
     }
     $objs = array();
     foreach ($all as $obj) {
         $o = Objects::findObject($obj->getObjectId());
         if ($o instanceof ContentDataObject) {
             $objs[] = $o;
         }
     }
     return $objs;
 }
function workspaces_quickadd_extra_fields($parameters) {
	if (array_var($parameters, 'dimension_id') == Dimensions::findByCode("workspaces")->getId()) {
		$parent_member = Members::findById(array_var($parameters, 'parent_id'));
		if ($parent_member instanceof Member && $parent_member->getObjectId() > 0) {
			$dimension_object = Objects::findObject($parent_member->getObjectId());
			
			$fields = $dimension_object->manager()->getPublicColumns();
			$color_columns = array();
			foreach ($fields as $f) {
				if ($f['type'] == DATA_TYPE_WSCOLOR) {
					$color_columns[] = $f['col'];
				}
			}
			foreach ($color_columns as $col) {
				foreach ($fields as &$f) {
					if ($f['col'] == $col && $dimension_object->columnExists($col)) {
						$color_code = $dimension_object->getColumnValue($col);
						echo '<input type="hidden" name="dim_obj['.$col.']" value="'.$color_code.'" />';
					}
				}
			}
		}
	}
}
 function getActivityData()
 {
     $user = Contacts::findById($this->getCreatedById());
     $object = Objects::findObject($this->getRelObjectId());
     if (!$user) {
         return false;
     }
     $icon_class = "";
     if ($object instanceof ProjectFile) {
         $path = explode("-", str_replace(".", "_", str_replace("/", "-", $object->getTypeString())));
         $acc = "";
         foreach ($path as $p) {
             $acc .= $p;
             $icon_class .= ' ico-' . $acc;
             $acc .= "-";
         }
     }
     // Build data depending on type
     if ($object) {
         if ($object instanceof Contact && $object->isUser()) {
             $type = "user";
         } else {
             $type = $object->getObjectTypeName();
         }
         $object_link = '<a style="font-weight:bold" href="' . $object->getObjectUrl() . '">&nbsp;' . '<span style="padding: 1px 0 3px 18px;" class="db-ico ico-unknown ico-' . $type . $icon_class . '"/>' . clean($object->getObjectName()) . '</a>';
     } else {
         $object_link = clean($this->getObjectName()) . '&nbsp;' . lang('object is deleted');
     }
     switch ($this->getAction()) {
         case ApplicationLogs::ACTION_EDIT:
         case ApplicationLogs::ACTION_ADD:
         case ApplicationLogs::ACTION_DELETE:
         case ApplicationLogs::ACTION_TRASH:
         case ApplicationLogs::ACTION_UNTRASH:
         case ApplicationLogs::ACTION_OPEN:
         case ApplicationLogs::ACTION_CLOSE:
         case ApplicationLogs::ACTION_ARCHIVE:
         case ApplicationLogs::ACTION_UNARCHIVE:
         case ApplicationLogs::ACTION_READ:
         case ApplicationLogs::ACTION_DOWNLOAD:
         case ApplicationLogs::ACTION_CHECKIN:
         case ApplicationLogs::ACTION_CHECKOUT:
             if ($object) {
                 return lang('activity ' . $this->getAction(), lang('the ' . $type), $user->getDisplayName(), $object_link);
             }
         case ApplicationLogs::ACTION_SUBSCRIBE:
         case ApplicationLogs::ACTION_UNSUBSCRIBE:
             $user_ids = explode(",", $this->getLogData());
             if (count($user_ids) < 8) {
                 $users_str = "";
                 foreach ($user_ids as $usid) {
                     $su = Contacts::findById($usid);
                     if ($su instanceof Contact) {
                         $users_str .= '<a style="font-weight:bold" href="' . $su->getObjectUrl() . '">&nbsp;<span style="padding: 0 0 3px 18px;" class="db-ico ico-unknown ico-user"/>' . clean($su->getObjectName()) . '</a>, ';
                     }
                 }
                 if (count($user_ids) == 1) {
                     $users_text = substr(trim($users_str), 0, -1);
                 } else {
                     $users_text = lang('x users', count($user_ids), ": {$users_str}");
                 }
             } else {
                 $users_text = lang('x users', count($user_ids), "");
             }
             if ($object) {
                 return lang('activity ' . $this->getAction(), lang('the ' . $object->getObjectTypeName()), $user->getDisplayName(), $object_link, $users_text);
             }
         case ApplicationLogs::ACTION_COMMENT:
             if ($object) {
                 return lang('activity ' . $this->getAction(), lang('the ' . $object->getRelObject()->getObjectTypeName()), $user->getDisplayName(), $object_link, $this->getLogData());
             }
         case ApplicationLogs::ACTION_LINK:
         case ApplicationLogs::ACTION_UNLINK:
             $exploded = explode(":", $this->getLogData());
             $linked_object = Objects::findObject($exploded[1]);
             if ($linked_object instanceof ApplicationDataObject) {
                 $icon_class = "";
                 if ($linked_object instanceof ProjectFile) {
                     $path = explode("-", str_replace(".", "_", str_replace("/", "-", $linked_object->getTypeString())));
                     $acc = "";
                     foreach ($path as $p) {
                         $acc .= $p;
                         $icon_class .= ' ico-' . $acc;
                         $acc .= "-";
                     }
                 }
                 $linked_object_link = '<a style="font-weight:bold" href="' . $linked_object->getObjectUrl() . '">&nbsp;<span style="padding: 1px 0 3px 18px;" class="db-ico ico-unknown ico-' . $linked_object->getObjectTypeName() . $icon_class . '"/>' . clean($linked_object->getObjectName()) . '</a>';
             } else {
                 $linked_object_link = '';
             }
             if ($object) {
                 return lang('activity ' . $this->getAction(), lang('the ' . $object->getObjectTypeName()), $user->getDisplayName(), $object_link, $linked_object instanceof ApplicationDataObject ? lang('the ' . $linked_object->getObjectTypeName()) : '', $linked_object_link);
             }
         case ApplicationLogs::ACTION_LOGIN:
         case ApplicationLogs::ACTION_LOGOUT:
             return lang('activity ' . $this->getAction(), $user->getDisplayName());
             /*FIXME when D&D is implemented case ApplicationLogs::ACTION_MOVE :
             			$exploded = explode(";", $this->getLogData());
             			$to_str = "";
             			$from_str = "";
             			foreach ($exploded as $str) {
             				if (str_starts_with($str, "from:")) {
             					$wsids_csv = str_replace("from:", "", $str);
             					$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
             					if (is_array($wsids) && count($wsids) > 0) {
             						$from_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
             					}
             				} else if (str_starts_with($str, "to:")) {
             					$wsids_csv = str_replace("to:", "", $str);
             					$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
             					if (is_array($wsids) && count($wsids) > 0) {
             						$to_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
             					}						
             				}
             			}
             			if($object){
             				if ($from_str != "" && $to_str != "") {						
             					return lang('activity ' . $this->getAction() . ' from to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $from_str, $to_str);
             				} else if ($from_str != "") {
             					return lang('activity ' . $this->getAction() . ' from', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $from_str);
             				} else if ($to_str != "") {
             					return lang('activity ' . $this->getAction() . ' to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $to_str);
             				} else {
             					return lang('activity ' . $this->getAction() . ' no ws', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link);
             				}
             			}		
             		case ApplicationLogs::ACTION_COPY :				
             			$to_str = "";
             			$wsids_csv = str_replace("to:", "", $this->getLogData());
             			$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
             			if (is_array($wsids) && count($wsids) > 0) {
             				$to_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
             			}
             			if($object){
             				if ($to_str != "") {
             					return lang('activity ' . $this->getAction() . ' to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $to_str);
             				} 
             			}else{
             				if ($to_str != "") {
             					return lang('activity ' . $this->getAction() . ' to', lang('the '.$this->getRelObjectManager()), $user->getDisplayName(), $object_link, $to_str);
             				}
             			}	*/
         /*FIXME when D&D is implemented case ApplicationLogs::ACTION_MOVE :
         			$exploded = explode(";", $this->getLogData());
         			$to_str = "";
         			$from_str = "";
         			foreach ($exploded as $str) {
         				if (str_starts_with($str, "from:")) {
         					$wsids_csv = str_replace("from:", "", $str);
         					$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
         					if (is_array($wsids) && count($wsids) > 0) {
         						$from_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
         					}
         				} else if (str_starts_with($str, "to:")) {
         					$wsids_csv = str_replace("to:", "", $str);
         					$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
         					if (is_array($wsids) && count($wsids) > 0) {
         						$to_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
         					}						
         				}
         			}
         			if($object){
         				if ($from_str != "" && $to_str != "") {						
         					return lang('activity ' . $this->getAction() . ' from to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $from_str, $to_str);
         				} else if ($from_str != "") {
         					return lang('activity ' . $this->getAction() . ' from', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $from_str);
         				} else if ($to_str != "") {
         					return lang('activity ' . $this->getAction() . ' to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $to_str);
         				} else {
         					return lang('activity ' . $this->getAction() . ' no ws', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link);
         				}
         			}		
         		case ApplicationLogs::ACTION_COPY :				
         			$to_str = "";
         			$wsids_csv = str_replace("to:", "", $this->getLogData());
         			$wsids = array_intersect(explode(",", logged_user()->getActiveProjectIdsCSV()), explode(",", $wsids_csv));
         			if (is_array($wsids) && count($wsids) > 0) {
         				$to_str = '<span class="project-replace">' . implode(",", $wsids) . '</span>';
         			}
         			if($object){
         				if ($to_str != "") {
         					return lang('activity ' . $this->getAction() . ' to', lang('the '.$object->getObjectTypeName()), $user->getDisplayName(), $object_link, $to_str);
         				} 
         			}else{
         				if ($to_str != "") {
         					return lang('activity ' . $this->getAction() . ' to', lang('the '.$this->getRelObjectManager()), $user->getDisplayName(), $object_link, $to_str);
         				}
         			}	*/
         default:
             return false;
     }
     return false;
 }
 function re_render_custom_properties()
 {
     $object = Objects::findObject(array_var($_GET, 'id'));
     if (!$object) {
         // if id == 0 object is new, then a dummy object is created to render the properties.
         $object = new ProjectMessage();
     }
     $html = render_object_custom_properties($object, array_var($_GET, 'req'), array_var($_GET, 'co_type'));
     $scripts = array();
     $initag = "<script>";
     $endtag = "</script>";
     $pos = strpos($html, $initag);
     while ($pos !== FALSE) {
         $end_pos = strpos($html, $endtag, $pos);
         if ($end_pos === FALSE) {
             break;
         }
         $ini = $pos + strlen($initag);
         $sc = substr($html, $ini, $end_pos - $ini);
         if (!str_starts_with(trim($sc), "og.addTableCustomPropertyRow")) {
             // do not add repeated functions
             $scripts[] = $sc;
         }
         $pos = strpos($html, $initag, $end_pos);
     }
     foreach ($scripts as $sc) {
         $html = str_replace("{$initag}{$sc}{$endtag}", "", $html);
     }
     ajx_current("empty");
     ajx_extra_data(array("html" => $html, 'scripts' => implode("", $scripts)));
 }
	function quick_add_files() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		$file_data = array_var($_POST, 'file');

		$file = new ProjectFile();
			
		tpl_assign('file', $file);
		tpl_assign('file_data', $file_data);
		tpl_assign('genid', array_var($_GET, 'genid'));
                tpl_assign('object_id', array_var($_GET, 'object_id'));
			
		if (is_array(array_var($_POST, 'file'))) {
			//$this->setLayout("html");
			$upload_option = array_var($file_data, 'upload_option');
			try {
				DB::beginWork();
				
				$type = array_var($file_data, 'type');
				$file->setType($type);
				$file->setFilename(array_var($file_data, 'name'));
				$file->setFromAttributes($file_data);
				
				$file->setIsVisible(true);
				
				$file->save();
				$file->subscribeUser(logged_user());
					
				if($file->getType() == ProjectFiles::TYPE_DOCUMENT){
					// handle uploaded file
					$upload_id = array_var($file_data, 'upload_id');
					$uploaded_file = array_var($_SESSION, $upload_id, array());
					$revision = $file->handleUploadedFile($uploaded_file, true); // handle uploaded file
					@unlink($uploaded_file['tmp_name']);
					unset($_SESSION[$upload_id]);
				} else if ($file->getType() == ProjectFiles::TYPE_WEBLINK) {
					$url = array_var($file_data, 'url', '');
					if ($url && strpos($url, ':') === false) {
						$url = $this->protocol . $url;
						$file->setUrl($url);
						$file->save();
					}
					$revision = new ProjectFileRevision();
					$revision->setFileId($file->getId());
					$revision->setRevisionNumber($file->getNextRevisionNumber());
					$revision->setFileTypeId(FileTypes::getByExtension('webfile')->getId());
					$revision->setTypeString($file->getUrl());
					$revision->setRepositoryId('webfile');
					$revision_comment = array_var($file_data, 'revision_comment', lang('initial versions'));
					$revision->setComment($revision_comment);
					$revision->save();
				}

				$member_ids = array();
				$object_controller = new ObjectController();
				if(count(active_context_members(false)) > 0 ){
					$object_controller->add_to_members($file, active_context_members(false));
				}elseif(array_var($file_data, 'object_id')){
					$object = Objects::findObject(array_var($file_data, 'object_id'));
					if ($object instanceof ContentDataObject) {
						$member_ids = $object->getMemberIds();
						$object_controller->add_to_members($file, $member_ids);
					} else {
						// add only to logged_user's person member
						$object_controller->add_to_members($file, array());
					}
				} else {
					// add only to logged_user's person member
					$object_controller->add_to_members($file, array());
				}
				
				DB::commit();
				
				ajx_extra_data(array("file_id" => $file->getId()));
				ajx_extra_data(array("file_name" => $file->getFilename()));
				ajx_extra_data(array("icocls" => 'ico-file ico-' . str_replace(".", "_", str_replace("/", "-", $file->getTypeString()))));

				if (!array_var($_POST, 'no_msg')) {
					flash_success(lang('success add file', $file->getFilename()));
				}
				ajx_current("empty");
				
			} catch(Exception $e) {
				DB::rollback();
				flash_error($e->getMessage());
				ajx_current("empty");

				// If we uploaded the file remove it from repository
				if(isset($revision) && ($revision instanceof ProjectFileRevision) && FileRepository::isInRepository($revision->getRepositoryId())) {
					FileRepository::deleteFile($revision->getRepositoryId());
				} // if
			} // try
		} // if
	} // quick_add_files
 function add_to()
 {
     if (!can_manage_templates(logged_user())) {
         flash_error(lang("no access permissions"));
         ajx_current("empty");
         return;
     }
     $manager = array_var($_GET, 'manager');
     $id = get_id();
     $object = Objects::findObject($id);
     $template_id = array_var($_GET, 'template');
     if ($template_id) {
         $template = COTemplates::findById($template_id);
         if ($template instanceof COTemplate) {
             try {
                 DB::beginWork();
                 $template->addObject($object);
                 DB::commit();
                 flash_success(lang('success add object to template'));
                 ajx_current("start");
             } catch (Exception $e) {
                 DB::rollback();
                 flash_error($e->getMessage());
             }
         }
     }
     tpl_assign('templates', COTemplates::findAll());
     tpl_assign("object", $object);
 }
Exemple #14
0
<?php    
    $options = explode(",",user_config_option("filters_dashboard"));
    
    $activities =  ApplicationLogs::getLastActivities();
    $limit = $options[2];
    $acts = array();
    $acts['data'] = array();
    foreach($activities as $activity){
        $user = Contacts::findById($activity->getCreatedById());
        if ($activity->getLogData() == 'member deleted') {
        	$object = Members::findById($activity->getRelObjectId());
        	$member_deleted = true;
        } else {
        	$object = Objects::findObject($activity->getRelObjectId());
        }
        
        if($object || $member_deleted){
            $key = $activity->getRelObjectId() . "-" . $activity->getCreatedById();

            if(count($acts['data']) < ($limit*2)){
                if(!array_key_exists($key, $acts['data'])){
                    $acts['data'][$key] = $object;
                    $acts['created_by'][$key] = $user;
                    $acts['act_data'][$key] = $activity->getActivityDataView($user,$object);
                    $acts['date'][$key] = $activity->getCreatedOn() instanceof DateTimeValue ? friendly_date($activity->getCreatedOn()) : lang('n/a');
                }else{
                    $acts['data'][$key] = $object;
                    $acts['created_by'][$key] = $user;
                    $acts['act_data'][$key] = $activity->getActivityDataView($user,$object,true);
                    $acts['date'][$key] = $activity->getCreatedOn() instanceof DateTimeValue ? friendly_date($activity->getCreatedOn()) : lang('n/a');
                }            
 private function trash($request)
 {
     $response = false;
     if ($id = $request['id']) {
         if ($object = Objects::findObject($id)) {
             if ($object->canDelete(logged_user())) {
                 try {
                     $object->trash();
                     Hook::fire('after_object_trash', $object, $null);
                     $response = true;
                 } catch (Exception $e) {
                     $response = false;
                 }
             }
         }
     }
     return $this->response('json', $response);
 }
 /**
  * Used for Drag & Drop, adds objects to a member
  * @author alvaro
  */
 function add_objects_to_member()
 {
     $ids = json_decode(array_var($_POST, 'objects'));
     $mem_id = array_var($_POST, 'member');
     if (!is_array($ids) || count($ids) == 0) {
         ajx_current("empty");
         return;
     }
     $member = Members::findById($mem_id);
     try {
         DB::beginWork();
         $objects = array();
         $from = array();
         foreach ($ids as $oid) {
             /* @var $obj ContentDataObject */
             $obj = Objects::findObject($oid);
             $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId())));
             if (!$dim_obj_type_content instanceof DimensionObjectTypeContent) {
                 continue;
             }
             if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) {
                 $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $member->getDimensionId() . " AND om.object_id=" . $obj->getId());
                 $row = $db_res->fetchRow();
                 if (array_var($row, 'old_members') != "") {
                     $from[$obj->getId()] = $row['old_members'];
                 }
                 // remove from previous members
                 ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $member->getDimensionId() . ')');
             }
             $obj->addToMembers(array($member));
             $obj->addToSharingTable();
             $objects[] = $obj;
         }
         DB::commit();
         // add to application logs
         foreach ($objects as $object) {
             $action = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
             $log_data = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId();
             ApplicationLogs::instance()->createLog($object, $action, false, true, true, $log_data);
         }
         $lang_key = count($ids) > 1 ? 'objects moved to member success' : 'object moved to member success';
         flash_success(lang($lang_key, $member->getName()));
         if (array_var($_POST, 'reload')) {
             ajx_current('reload');
         } else {
             ajx_current('empty');
         }
     } catch (Exception $e) {
         DB::rollback();
         ajx_current("empty");
         flash_error(lang('unable to move objects'));
     }
 }
 function repetitive_tasks_related($task, $action, $type_related = "", $task_data = array())
 {
     //I find all those related to the task to find out if the original
     $task_related = ProjectTasks::findByRelated($task->getObjectId());
     if (!$task_related) {
         //is not the original as the original look plus other related
         if ($task->getOriginalTaskId() != "0") {
             $task_related = ProjectTasks::findByTaskAndRelated($task->getObjectId(), $task->getOriginalTaskId());
         }
     }
     if ($task_related) {
         switch ($action) {
             case "edit":
                 foreach ($task_related as $t_rel) {
                     if ($type_related == "news") {
                         if ($task->getStartDate() <= $t_rel->getStartDate() && $task->getDueDate() <= $t_rel->getDueDate()) {
                             $this->repetitive_task_related_edit($t_rel, $task_data);
                         }
                     } else {
                         $this->repetitive_task_related_edit($t_rel, $task_data);
                     }
                 }
                 break;
             case "delete":
                 $delete_task = array();
                 foreach ($task_related as $t_rel) {
                     $task_rel = Objects::findObject($t_rel->getId());
                     if ($type_related == "news") {
                         if ($task->getStartDate() <= $t_rel->getStartDate() && $task->getDueDate() <= $t_rel->getDueDate()) {
                             $delete_task[] = $t_rel->getId();
                             $task_rel->trash();
                         }
                     } else {
                         $delete_task[] = $t_rel->getId();
                         $task_rel->trash();
                     }
                 }
                 return $delete_task;
                 break;
             case "archive":
                 $archive_task = array();
                 foreach ($task_related as $t_rel) {
                     $task_rel = Objects::findObject($t_rel->getId());
                     if ($type_related == "news") {
                         if ($task->getStartDate() <= $t_rel->getStartDate() && $task->getDueDate() <= $t_rel->getDueDate()) {
                             $archive_task[] = $t_rel->getId();
                             $t_rel->archive();
                         }
                     } else {
                         $archive_task[] = $t_rel->getId();
                         $t_rel->archive();
                     }
                 }
                 return $archive_task;
                 break;
         }
     }
 }
Exemple #18
0
function groupObjectsByAssocObjColumnValue($objects, $column, $fk, &$parent_group = null)
{
    $groups = array();
    $grouped_objects = array();
    $i = 1;
    foreach ($objects as $obj) {
        $group = null;
        $rel_obj = Objects::findObject($obj->getColumnValue($fk));
        if (!$rel_obj instanceof ContentDataObject) {
            $gb_val = 'unclassified';
        } else {
            $gb_val = $rel_obj->getColumnValue($column);
            if ($gb_val == 0) {
                $gb_val = 'unclassified';
            }
        }
        foreach ($groups as $g) {
            if (array_var($g, 'id') == $gb_val) {
                $group = $g;
            }
        }
        if (is_null($group)) {
            if ($gb_val != 'unclassified' && in_array($column, $rel_obj->manager()->getExternalColumns())) {
                $name = Objects::findObject($rel_obj->getColumnValue($column))->getObjectName();
            } else {
                $name = lang("{$column} {$gb_val}");
            }
            $group = array('group' => array('id' => $gb_val, 'name' => $name, 'pid' => 0), 'subgroups' => array());
            $groups[$gb_val] = $group;
        }
        if (!isset($grouped_objects[$gb_val])) {
            $grouped_objects[$gb_val] = array();
        }
        $grouped_objects[$gb_val][] = $obj;
    }
    if ($parent_group != null) {
        foreach ($groups as $mid => $group) {
            $parent_group['subgroups'][$mid] = $group;
        }
    }
    return array('groups' => $groups, 'grouped_objects' => $grouped_objects);
}
 function get_object_properties()
 {
     $obj_id = get_id();
     $obj = Objects::findObject($obj_id);
     $props = array();
     $manager = $obj->manager();
     $objectProperties = $manager->getTemplateObjectProperties();
     /**
      * Allow to add/edit/delete template object properties
      */
     Hook::fire('get_template_object_properties', $type, $objectProperties);
     foreach ($objectProperties as $property) {
         $props[] = array('id' => $property['id'], 'name' => lang('field ProjectTasks ' . $property['id']), 'type' => $property['type']);
     }
     ajx_current("empty");
     ajx_extra_data(array('properties' => $props));
 }
 /**
  * 
  * 
  */
 public function activity_feed()
 {
     ajx_set_no_back(true);
     require_javascript("og/modules/dashboardComments.js");
     require_javascript("jquery/jquery.scrollTo-min.js");
     /* get query parameters */
     $filesPerPage = config_option('files_per_page');
     $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0;
     $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage;
     $order = array_var($_GET, 'sort');
     $orderdir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $typeCSV = array_var($_GET, 'type');
     $types = null;
     if ($typeCSV) {
         $types = explode(",", $typeCSV);
     }
     $name_filter = array_var($_GET, 'name');
     $linked_obj_filter = array_var($_GET, 'linkedobject');
     $object_ids_filter = '';
     if (!is_null($linked_obj_filter)) {
         $linkedObject = Objects::findObject($linked_obj_filter);
         $objs = $linkedObject->getLinkedObjects();
         foreach ($objs as $obj) {
             $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId();
         }
     }
     $filters = array();
     if (!is_null($types)) {
         $filters['types'] = $types;
     }
     if (!is_null($name_filter)) {
         $filters['name'] = $name_filter;
     }
     if ($object_ids_filter != '') {
         $filters['object_ids'] = $object_ids_filter;
     }
     $user = array_var($_GET, 'user');
     $trashed = array_var($_GET, 'trashed', false);
     $archived = array_var($_GET, 'archived', false);
     /* if there's an action to execute, do so */
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $result = Objects::getObjectsFromContext(active_context(), null, null, false, false, array('object_ids' => implode(",", $ids)));
         $objects = $result->objects;
         list($succ, $err) = $this->do_delete_objects($objects);
         if ($err > 0) {
             flash_error(lang('error delete objects', $err));
         } else {
             flash_success(lang('success delete objects', $succ));
         }
     } else {
         if (array_var($_GET, 'action') == 'delete_permanently') {
             $ids = explode(',', array_var($_GET, 'objects'));
             $result = Objects::getObjectsFromContext(active_context(), null, null, true, false, array('object_ids' => implode(",", $ids)));
             $objects = $result->objects;
             list($succ, $err) = $this->do_delete_objects($objects, true);
             if ($err > 0) {
                 flash_error(lang('error delete objects', $err));
             }
             if ($succ > 0) {
                 flash_success(lang('success delete objects', $succ));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasread') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true);
             } else {
                 if (array_var($_GET, 'action') == 'markasunread') {
                     $ids = explode(',', array_var($_GET, 'objects'));
                     list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false);
                 } else {
                     if (array_var($_GET, 'action') == 'empty_trash_can') {
                         $result = Objects::getObjectsFromContext(active_context(), 'trashed_on', 'desc', true);
                         $objects = $result->objects;
                         list($succ, $err) = $this->do_delete_objects($objects, true);
                         if ($err > 0) {
                             flash_error(lang('error delete objects', $err));
                         }
                         if ($succ > 0) {
                             flash_success(lang('success delete objects', $succ));
                         }
                     } else {
                         if (array_var($_GET, 'action') == 'archive') {
                             $ids = explode(',', array_var($_GET, 'objects'));
                             list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive');
                             if ($err > 0) {
                                 flash_error(lang('error archive objects', $err));
                             } else {
                                 flash_success(lang('success archive objects', $succ));
                             }
                         } else {
                             if (array_var($_GET, 'action') == 'unarchive') {
                                 $ids = explode(',', array_var($_GET, 'objects'));
                                 list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive');
                                 if ($err > 0) {
                                     flash_error(lang('error unarchive objects', $err));
                                 } else {
                                     flash_success(lang('success unarchive objects', $succ));
                                 }
                             } else {
                                 if (array_var($_GET, 'action') == 'unclassify') {
                                     $ids = explode(',', array_var($_GET, 'objects'));
                                     $err = 0;
                                     $succ = 0;
                                     foreach ($ids as $id) {
                                         $split = explode(":", $id);
                                         $type = $split[0];
                                         if ($type == 'MailContents') {
                                             $email = MailContents::findById($split[1]);
                                             if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                                                 if (MailController::do_unclassify($email)) {
                                                     $succ++;
                                                 } else {
                                                     $err++;
                                                 }
                                             } else {
                                                 $err++;
                                             }
                                         }
                                     }
                                     if ($err > 0) {
                                         flash_error(lang('error unclassify emails', $err));
                                     } else {
                                         flash_success(lang('success unclassify emails', $succ));
                                     }
                                 } else {
                                     if (array_var($_GET, 'action') == 'restore') {
                                         $errorMessage = null;
                                         $ids = explode(',', array_var($_GET, 'objects'));
                                         $success = 0;
                                         $error = 0;
                                         foreach ($ids as $id) {
                                             $obj = Objects::findObject($id);
                                             if ($obj->canDelete(logged_user())) {
                                                 try {
                                                     $obj->untrash($errorMessage);
                                                     ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH);
                                                     $success++;
                                                 } catch (Exception $e) {
                                                     $error++;
                                                 }
                                             } else {
                                                 $error++;
                                             }
                                         }
                                         if ($success > 0) {
                                             flash_success(lang("success untrash objects", $success));
                                         }
                                         if ($error > 0) {
                                             $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage;
                                             flash_error($errorString);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     /*FIXME else if (array_var($_GET, 'action') == 'move') {
     			$wsid = array_var($_GET, "moveTo");
     			$destination = Projects::findById($wsid);
     			if (!$destination instanceof Project) {
     				$resultMessage = lang('project dnx');
     				$resultCode = 1;
     			} else if (!can_add(logged_user(), $destination, 'ProjectMessages')) {
     				$resultMessage = lang('no access permissions');
     				$resultCode = 1;
     			} else {
     				$ids = explode(',', array_var($_GET, 'objects'));
     				$count = 0;
     				DB::beginWork();
     				foreach ($ids as $id) {
     					$split = explode(":", $id);
     					$type = $split[0];
     					$obj = Objects::findObject($split[1]);
     					$mantainWs = array_var($_GET, "mantainWs");
     					if ($type != 'Projects' && $obj->canEdit(logged_user())) {
     						if ($type == 'MailContents') {
     							$email = MailContents::findById($split[1]);
     							$conversation = MailContents::getMailsFromConversation($email);
     							foreach ($conversation as $conv_email) {
     								$count += MailController::addEmailToWorkspace($conv_email->getId(), $destination, $mantainWs);
     								if (array_var($_GET, 'classify_atts') && $conv_email->getHasAttachments()) {
     									MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
     									$classification_data = array();
     									for ($j=0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
     										$classification_data["att_".$j] = true;		
     									}
     									$tags = implode(",", $conv_email->getTagNames());
     									MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($destination), $mantainWs, $tags);
     								}								
     							}
     							$count++;
     						} else {
     							if (!$mantainWs || $type == 'ProjectTasks' || $type == 'ProjectMilestones') {
     								$removed = "";
     								$ws = $obj->getWorkspaces();
     								foreach ($ws as $w) {
     									if (can_add(logged_user(), $w, $type)) {
     										$obj->removeFromWorkspace($w);
     										$removed .= $w->getId() . ",";
     									}
     								}
     								$removed = substr($removed, 0, -1);
     								$log_action = ApplicationLogs::ACTION_MOVE;
     								$log_data = ($removed == "" ? "" : "from:$removed;") . "to:$wsid";
     							} else {
     								$log_action = ApplicationLogs::ACTION_COPY;
     								$log_data = "to:$wsid";
     							}
     							$obj->addToWorkspace($destination);
     							ApplicationLogs::createLog($obj, $log_action, false, null, true, $log_data);
     							$count++;
     						}
     					}
     				}
     				if ($count > 0) {
     					$reload = true;
     					DB::commit();
     					flash_success(lang("success move objects", $count));
     				} else {
     					DB::rollback();
     				}
     			}
     		}*/
     $filterName = array_var($_GET, 'name');
     $result = null;
     $context = active_context();
     $obj_type_types = array('content_object');
     if (array_var($_GET, 'include_comments')) {
         $obj_type_types[] = 'comment';
     }
     $pagination = Objects::getObjects($context, $start, $limit, $order, $orderdir, $trashed, $archived, $filters, $start, $limit, $obj_type_types);
     $result = $pagination->objects;
     $total_items = $pagination->total;
     if (!$result) {
         $result = array();
     }
     /* prepare response object */
     $info = array();
     foreach ($result as $obj) {
         $info_elem = $obj->getArrayInfo($trashed, $archived);
         $instance = Objects::instance()->findObject($info_elem['object_id']);
         $info_elem['url'] = $instance->getViewUrl();
         if (method_exists($instance, "getText")) {
             $info_elem['content'] = $instance->getText();
         }
         $info_elem['picture'] = $instance->getCreatedBy()->getPictureUrl();
         $info_elem['friendly_date'] = friendly_date($instance->getCreatedOn());
         $info_elem['comment'] = $instance->getComments();
         /* @var $instance Contact  */
         if ($instance instanceof Contact) {
             if ($instance->isCompany()) {
                 $info_elem['icon'] = 'ico-company';
                 $info_elem['type'] = 'company';
             }
         }
         $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId());
         $info_elem['manager'] = get_class($instance->manager());
         $info[] = $info_elem;
     }
     $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info);
     tpl_assign("feeds", $listing);
 }
 function add_timespan()
 {
     $object_id = get_id('object_id');
     $object = Objects::findObject($object_id);
     if (!$object instanceof ContentDataObject || !$object->canAddTimeslot(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $timeslot_data = array_var($_POST, 'timeslot');
     $hours = array_var($timeslot_data, 'hours');
     $minutes = array_var($timeslot_data, 'minutes');
     if (strpos($hours, ',') && !strpos($hours, '.')) {
         $hours = str_replace(',', '.', $hours);
     }
     if ($minutes) {
         $min = str_replace('.', '', $minutes / 6);
         $hours = $hours + ("0." . $min);
     }
     $timeslot = new Timeslot();
     $dt = DateTimeValueLib::now();
     $dt2 = DateTimeValueLib::now();
     $timeslot->setEndTime($dt);
     $dt2 = $dt2->add('h', -$hours);
     $timeslot->setStartTime($dt2);
     $timeslot->setDescription(array_var($timeslot_data, 'description'));
     $timeslot->setContactId(array_var($timeslot_data, 'contact_id', logged_user()->getId()));
     $timeslot->setRelObjectId($object_id);
     $billing_category_id = logged_user()->getDefaultBillingId();
     $bc = BillingCategories::findById($billing_category_id);
     if ($bc instanceof BillingCategory) {
         $timeslot->setBillingId($billing_category_id);
         $hourly_billing = $bc->getDefaultValue();
         $timeslot->setHourlyBilling($hourly_billing);
         $timeslot->setFixedBilling($hourly_billing * $hoursToAdd);
         $timeslot->setIsFixedBilling(false);
     }
     try {
         DB::beginWork();
         $timeslot->save();
         /*	dont add timeslots to members, members are taken from the related object
         			$object_controller = new ObjectController();
         			$object_controller->add_to_members($timeslot, $object->getMemberIds());
         		*/
         ApplicationLogs::createLog($timeslot, ApplicationLogs::ACTION_OPEN);
         $task = ProjectTasks::findById($object_id);
         if ($task->getTimeEstimate() > 0) {
             $timeslots = $task->getTimeslots();
             if (count($timeslots) == 1) {
                 $task->setPercentCompleted(0);
             }
             $timeslot_percent = round($hours * 100 / ($task->getTimeEstimate() / 60));
             $total_percentComplete = $timeslot_percent + $task->getPercentCompleted();
             if ($total_percentComplete < 0) {
                 $total_percentComplete = 0;
             }
             $task->setPercentCompleted($total_percentComplete);
             $task->save();
             $this->notifier_work_estimate($task);
         }
         DB::commit();
         flash_success(lang('success create timeslot'));
         ajx_current("reload");
     } catch (Exception $e) {
         DB::rollback();
         ajx_current("empty");
         flash_error($e->getMessage());
     }
 }
 static function objectNotification($object, $people, $sender, $notification, $description = null, $descArgs = null, $properties = array(), $links = array())
 {
     if (!is_array($people) || !count($people)) {
         return;
     }
     if ($sender instanceof Contact) {
         $sendername = $sender->getObjectName();
         $senderemail = $sender->getEmailAddress();
         $senderid = $sender->getId();
     } else {
         $sendername = owner_company()->getObjectName();
         $senderemail = owner_company()->getEmailAddress();
         if (!is_valid_email($senderemail)) {
             $senderemail = '*****@*****.**';
         }
         $senderid = 0;
     }
     $type = $object->getObjectTypeName();
     $typename = lang($object->getObjectTypeName());
     $name = $object instanceof Comment ? $object->getRelObject()->getObjectName() : $object->getObjectName();
     $assigned_to = "";
     $assigned_by = "";
     if ($object instanceof ProjectTask) {
         if ($object->getAssignedTo() instanceof Contact) {
             $assigned_to = $object->getAssignedToName();
             if ($object->getAssignedBy() instanceof Contact) {
                 $assigned_by = $object->getAssignedBy()->getObjectName();
             }
         }
     }
     $text = "";
     //text, descripction or revision comment
     if ($object->columnExists('text') && trim($object->getColumnValue('text'))) {
         if ($object->getObjectTypeId() == "3" || $object->getObjectTypeId() == "5") {
             if (config_option("wysiwyg_tasks") || config_option("wysiwyg_messages")) {
                 $text = purify_html(nl2br($object->getColumnValue('text')));
             } else {
                 $text = escape_html_whitespace("\n" . $object->getColumnValue('text'));
             }
         } else {
             $text = escape_html_whitespace("\n" . $object->getColumnValue('text'));
         }
     }
     if ($object->columnExists('description') && trim($object->getColumnValue('description'))) {
         if ($object->getObjectTypeId() == "3" || $object->getObjectTypeId() == "5") {
             if (config_option("wysiwyg_tasks") || config_option("wysiwyg_messages")) {
                 $text = purify_html(nl2br($object->getColumnValue('description')));
             } else {
                 $text = escape_html_whitespace("\n" . $object->getColumnValue('description'));
             }
         } else {
             $text = escape_html_whitespace("\n" . $object->getColumnValue('description'));
         }
     }
     $text_comment = "";
     if ($object instanceof ProjectFile && $object->getType() == ProjectFiles::TYPE_DOCUMENT) {
         $revision = $object->getLastRevision();
         if (trim($revision->getComment())) {
             $text_comment = escape_html_whitespace("\n" . $revision->getComment());
         }
     }
     //context
     $contexts = array();
     $members = $object instanceof Comment ? $object->getRelObject()->getMembers() : $object->getMembers();
     // Do not send context when edit a user
     if (!($object instanceof Contact && $notification == 'modified' && $object->getUserType() > 0)) {
         if (count($members) > 0) {
             foreach ($members as $member) {
                 $dim = $member->getDimension();
                 if ($dim->getIsManageable()) {
                     /* @var $member Member */
                     $parent_members = $member->getAllParentMembersInHierarchy();
                     $parents_str = '';
                     foreach ($parent_members as $pm) {
                         /* @var $pm Member */
                         if (!$pm instanceof Member) {
                             continue;
                         }
                         $parents_str .= '<span style="' . get_workspace_css_properties($pm->getMemberColor()) . '">' . $pm->getName() . '</span>';
                     }
                     if ($dim->getCode() == "customer_project" || $dim->getCode() == "customers") {
                         $obj_type = ObjectTypes::findById($member->getObjectTypeId());
                         if ($obj_type instanceof ObjectType) {
                             $contexts[$dim->getCode()][$obj_type->getName()][] = $parents_str . '<span style="' . get_workspace_css_properties($member->getMemberColor()) . '">' . $member->getName() . '</span>';
                         }
                     } else {
                         $contexts[$dim->getCode()][] = $parents_str . '<span style="' . get_workspace_css_properties($member->getMemberColor()) . '">' . $member->getName() . '</span>';
                     }
                 }
             }
         }
     }
     $attachments = array();
     try {
         if ($object instanceof ProjectFile && ($object->getAttachToNotification() || $object->getFileType() && $object->getFileType()->getIsImage() && config_option('show images in document notifications') && in_array($object->getTypeString(), ProjectFiles::$image_types))) {
             if (FileRepository::getBackend() instanceof FileRepository_Backend_FileSystem) {
                 $file_path = FileRepository::getBackend()->getFilePath($object->getLastRevision()->getRepositoryId());
             } else {
                 $file_path = ROOT . "/tmp/" . $object->getFilename();
                 $handle = fopen($file_path, 'wb');
                 fwrite($handle, $object->getLastRevision()->getFileContent(), $object->getLastRevision()->getFilesize());
                 fclose($handle);
             }
             $att_disposition = 'attachment';
             if (config_option('show images in document notifications') && in_array($object->getTypeString(), ProjectFiles::$image_types)) {
                 $att_disposition = 'inline';
             }
             $attachments[] = array('cid' => gen_id() . substr($senderemail, strpos($senderemail, '@')), 'path' => $file_path, 'type' => $object->getTypeString(), 'disposition' => $att_disposition, 'name' => $object->getFilename());
         }
     } catch (FileNotInRepositoryError $e) {
         // don't interrupt notifications.
     }
     if (trim($name) == "") {
         $name = lang($object->getObjectTypeName()) . " (" . lang('id') . ": " . $object->getId() . ")";
     }
     tpl_assign('object', $object);
     tpl_assign('title', $name);
     //title
     tpl_assign('by', $assigned_by);
     //by
     tpl_assign('asigned', $assigned_to);
     //assigned to
     tpl_assign('description', $text);
     //descripction
     tpl_assign('revision_comment', $text_comment);
     //revision_comment
     tpl_assign('contexts', $contexts);
     //contexts
     $emails = array();
     $grouped_people = self::buildPeopleGroups($people);
     foreach ($grouped_people as $pgroup) {
         $lang = array_var($pgroup, 'lang');
         $timezone = array_var($pgroup, 'tz');
         $group_users = array_var($pgroup, 'groups');
         // contains arrays of users, with max size = 20 each one, a single email is sent foreach user group
         foreach ($group_users as $users) {
             $to_addresses = array();
             foreach ($users as $user) {
                 if (logged_user() instanceof Contact && logged_user()->getId() == $user->getId()) {
                     $user->notify_myself = logged_user()->notify_myself;
                 }
                 if (($user->getId() != $senderid || $user->notify_myself) && ($object->canView($user) || $user->ignore_permissions_for_notifications)) {
                     $to_addresses[$user->getId()] = self::prepareEmailAddress($user->getEmailAddress(), $user->getObjectName());
                 }
             }
             // build notification
             if (count($to_addresses) > 0) {
                 if ($object instanceof Comment) {
                     $subscribers = $object->getRelObject()->getSubscribers();
                 } else {
                     $subscribers = $object->getSubscribers();
                 }
                 //ALL SUBSCRIBERS
                 if (count($subscribers) > 0) {
                     $string_subscriber = '';
                     $total_s = count($subscribers);
                     $c = 0;
                     foreach ($subscribers as $subscriber) {
                         $c++;
                         if ($c == $total_s && $total_s > 1) {
                             $string_subscriber .= " " . lang('and') . " ";
                         } else {
                             if ($c > 1) {
                                 $string_subscriber .= ", ";
                             }
                         }
                         $string_subscriber .= $subscriber->getFirstName();
                         if ($subscriber->getSurname() != "") {
                             $string_subscriber .= " " . $subscriber->getSurname();
                         }
                     }
                     tpl_assign('subscribers', $string_subscriber);
                     // subscribers
                 }
                 // send notification on user's locale and with user info
                 Localization::instance()->loadSettings($lang, ROOT . '/language');
                 if ($object instanceof Comment) {
                     $object_comment = Objects::findObject($object->getRelObjectId());
                     $object_type_name = $object_comment->getObjectTypeName();
                 } else {
                     $object_type_name = '';
                 }
                 $object_type = strtolower(lang($object_type_name));
                 if ($object_type_name != "") {
                     tpl_assign('object_comment_name', lang("the " . strtolower($object_type_name) . " notification"));
                     //object_comment_name
                 }
                 if (!isset($description)) {
                     $descArgs = array(clean($name), $sendername, $object_type, $object->getCreatedByDisplayName());
                     $description = "{$notification} notification {$type} desc";
                 } else {
                     //reminders
                     $date = "";
                     //due
                     if ($object->columnExists('due_date') && $object->getColumnValue('due_date')) {
                         if ($object->getColumnValue('due_date') instanceof DateTimeValue) {
                             $date = Localization::instance()->formatDescriptiveDate($object->getColumnValue('due_date'), $timezone);
                             $time = Localization::instance()->formatTime($object->getColumnValue('due_date'), $timezone);
                             if ($time > 0) {
                                 $date .= " " . $time;
                             }
                         }
                     }
                     //start
                     if ($object->columnExists('start') && $object->getColumnValue('start')) {
                         if ($object->getColumnValue('start') instanceof DateTimeValue) {
                             $date = Localization::instance()->formatDescriptiveDate($object->getColumnValue('start'), $timezone);
                             $time = Localization::instance()->formatTime($object->getColumnValue('start'), $timezone);
                             if ($time > 0) {
                                 $date .= " " . $time;
                             }
                         }
                     }
                     $descArgs = array(clean($name), $date != "" ? $date : $sendername, $object_type, $object->getCreatedByDisplayName(), $date);
                 }
                 tpl_assign('description_title', langA($description, $descArgs));
                 //description_title
                 tpl_assign('priority', '');
                 //priority
                 if ($object->columnExists('priority') && trim($object->getColumnValue('priority'))) {
                     if ($object->getColumnValue('priority') >= ProjectTasks::PRIORITY_URGENT) {
                         $priorityColor = "#FF0000";
                         $priority = lang('urgent priority');
                     } else {
                         if ($object->getColumnValue('priority') >= ProjectTasks::PRIORITY_HIGH) {
                             $priorityColor = "#FF9088";
                             $priority = lang('high priority');
                         } else {
                             if ($object->getColumnValue('priority') <= ProjectTasks::PRIORITY_LOW) {
                                 $priorityColor = "white";
                                 $priority = lang('low priority');
                             } else {
                                 $priorityColor = "#DAE3F0";
                                 $priority = lang('normal priority');
                             }
                         }
                     }
                     tpl_assign('priority', array($priority, $priorityColor));
                     //priority
                 }
                 //ESPECIAL ASSIGNED FOR EVENTS
                 tpl_assign('start', '');
                 //start
                 tpl_assign('time', '');
                 //time
                 tpl_assign('duration', '');
                 //duration
                 tpl_assign('guests', '');
                 // invitations
                 tpl_assign('start_date', '');
                 //start_date
                 tpl_assign('due_date', '');
                 //due_date
                 $event_ot = ObjectTypes::findByName('event');
                 if ($object->getObjectTypeId() == $event_ot->getId()) {
                     //start
                     if ($object->getStart() instanceof DateTimeValue) {
                         $date = Localization::instance()->formatDescriptiveDate($object->getStart(), $timezone);
                         $time = Localization::instance()->formatTime($object->getStart(), $timezone);
                         tpl_assign('start', $date);
                         //start
                         if ($object->getTypeId() != 2) {
                             tpl_assign('time', $time);
                             //time
                         }
                     }
                     if ($object->getTypeId() != 2) {
                         //duration
                         if ($object->getDuration() instanceof DateTimeValue) {
                             $durtime = $object->getDuration()->getTimestamp() - $object->getStart()->getTimestamp();
                             $durhr = $durtime / 3600 % 24;
                             //seconds per hour
                             tpl_assign('duration', $durhr . " hs");
                             //duration
                         }
                     } else {
                         tpl_assign('duration', lang('all day event'));
                         //duration
                     }
                     //invitations
                     $guests = "";
                     $send_link = array();
                     $invitations = EventInvitations::findAll(array('conditions' => 'event_id = ' . $object->getId()));
                     if (isset($invitations) && is_array($invitations)) {
                         foreach ($invitations as $inv) {
                             $inv_user = Contacts::findById($inv->getContactId());
                             if ($inv_user instanceof Contact) {
                                 if (can_access($inv_user, $object->getMembers(), ProjectEvents::instance()->getObjectTypeId(), ACCESS_LEVEL_READ)) {
                                     $state_desc = lang('pending response');
                                     if ($inv->getInvitationState() == 1) {
                                         $state_desc = lang('yes');
                                     } else {
                                         if ($inv->getInvitationState() == 2) {
                                             $state_desc = lang('no');
                                         } else {
                                             if ($inv->getInvitationState() == 3) {
                                                 $state_desc = lang('maybe');
                                             }
                                         }
                                     }
                                     $guests .= '<div style="line-height: 20px; clear:both;">';
                                     $guests .= '<div style="width: 35%;line-height: 20px; float: left;">' . clean($inv_user->getObjectName()) . '</div>';
                                     $guests .= '<div style="line-height: 20px; float: left;">' . $state_desc . '</div></div>';
                                 }
                                 if ($inv->getInvitationState() == 0) {
                                     $send_link[] = $inv_user->getId();
                                 }
                             }
                         }
                     }
                     tpl_assign('guests', $guests);
                     // invitations
                 } else {
                     //start date, due date or start
                     if ($object->columnExists('start_date') && $object->getColumnValue('start_date')) {
                         if ($object->getColumnValue('start_date') instanceof DateTimeValue) {
                             $date = Localization::instance()->formatDescriptiveDate($object->getColumnValue('start_date'), $timezone);
                             $time = Localization::instance()->formatTime($object->getColumnValue('start_date'), $timezone);
                             if ($time > 0) {
                                 $date .= " " . $time;
                             }
                         }
                         tpl_assign('start_date', $date);
                         //start_date
                     }
                     if ($object->columnExists('due_date') && $object->getColumnValue('due_date')) {
                         if ($object->getColumnValue('due_date') instanceof DateTimeValue) {
                             $date = Localization::instance()->formatDescriptiveDate($object->getColumnValue('due_date'), $timezone);
                             $time = Localization::instance()->formatTime($object->getColumnValue('due_date'), $timezone);
                             if ($time > 0) {
                                 $date .= " " . $time;
                             }
                         }
                         tpl_assign('due_date', $date);
                         //due_date
                     }
                 }
                 $toemail = $user->getEmailAddress();
                 try {
                     $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile());
                     if ($content != "") {
                         $file_path = ROOT . "/tmp/logo_empresa.png";
                         $handle = fopen($file_path, 'wb');
                         if ($handle) {
                             fwrite($handle, $content);
                             fclose($handle);
                             $attachments['logo'] = array('cid' => gen_id() . substr($toemail, strpos($toemail, '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png');
                         }
                     }
                 } catch (FileNotInRepositoryError $e) {
                     unset($attachments['logo']);
                 }
                 tpl_assign('attachments', $attachments);
                 // attachments
                 $from = self::prepareEmailAddress($senderemail, $sendername);
                 if (!$toemail) {
                     continue;
                 }
                 $subject = htmlspecialchars_decode(langA("{$notification} notification {$type}", $descArgs));
                 if ($object instanceof ProjectFile && $object->getDefaultSubject() != "") {
                     $subject = $object->getDefaultSubject();
                     tpl_assign('description_title', $subject);
                 }
                 $recipients_field = config_option('notification_recipients_field', 'to');
                 $emails[] = array("{$recipients_field}" => $to_addresses, "from" => self::prepareEmailAddress($senderemail, $sendername), "subject" => $subject, "body" => tpl_fetch(get_template_path('general', 'notifier')), "attachments" => $attachments);
             }
         }
     }
     self::queueEmails($emails);
     $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION;
     Localization::instance()->loadSettings($locale, ROOT . '/language');
 }
 function get_rendered_member_selectors()
 {
     $object_members = array();
     $objectId = 0;
     if (get_id()) {
         $object = Objects::findObject(get_id());
         $object_type_id = $object->manager()->getObjectTypeId();
         $object_members = $object->getMemberIds();
         $objectId = get_id();
     } else {
         $object_type_id = array_var($_GET, 'objtypeid');
         if (array_var($_GET, 'members')) {
             $object_members = explode(',', array_var($_GET, 'members'));
         }
     }
     if (count($object_members) == 0) {
         $object_members = active_context_members(false);
     }
     $genid = array_var($_GET, 'genid');
     $listeners = array();
     //ob_start — Turn on output buffering
     //no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
     ob_start();
     //get skipped dimensions for this view
     $view_name = array_var($_GET, 'view_name');
     $dimensions_to_show = explode(",", user_config_option($view_name . "_view_dimensions_combos"));
     $dimensions_to_skip = array_diff(get_user_dimensions_ids(), $dimensions_to_show);
     render_member_selectors($object_type_id, $genid, $object_members, array('listeners' => $listeners), $dimensions_to_skip, null, false);
     ajx_current("empty");
     //Gets the current buffer contents and delete current output buffer.
     //ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
     ajx_extra_data(array("htmlToAdd" => ob_get_clean()));
     ajx_extra_data(array("objectId" => $objectId));
 }
 function repetitive_event_related($event,$action,$type_related = "",$event_data = array()){
     //I find all those related to the event to find out if the original
     $event_related = ProjectEvents::findByRelated($event->getObjectId());
     if(!$event_related){
         //is not the original as the original look plus other related
         if($event->getOriginalEventId() != "0"){
             $event_related = ProjectEvents::findByEventAndRelated($event->getObjectId(),$event->getOriginalEventId());
         }
     }            
     if($event_related){
         switch($action){
                 case "edit":
                         foreach ($event_related as $e_rel){
                             if($type_related == "news"){
                                 if($event->getStart() <= $e_rel->getStart()){
                                     $this->repetitive_event_related_edit($e_rel,$event_data);
                                 }
                             }else{
                                 $this->repetitive_event_related_edit($e_rel,$event_data);
                             }                                    
                         }
                 break;
                 case "delete":
                         $delete_event = array();
                         foreach ($event_related as $e_rel){
                             $event_rel = Objects::findObject($e_rel->getId());   
                             if($type_related == "news"){
                                 if($event->getStart() <= $e_rel->getStart()){
                                     $delete_event[] = $e_rel->getId();                                                                             
                                     $event_rel->trash(); 
                                 }
                             }else{
                                 $delete_event[] = $e_rel->getId();                                                                             
                                 $event_rel->trash(); 
                             }                                                                        
                         }
                         return $delete_event;
                 break;
                 case "archive":
                         $archive_event = array();
                         foreach ($event_related as $e_rel){
                             $event_rel = Objects::findObject($e_rel->getId());                                    
                             if($type_related == "news"){
                                 if($event->getStart() <= $e_rel->getStart()){
                                     $archive_event[] = $e_rel->getId();                                                                            
                                     $e_rel->archive();  
                                 }
                             }else{
                                 $archive_event[] = $e_rel->getId();                                                                            
                                 $e_rel->archive();
                             }
                         }
                         return $archive_event;
                 break;
         }
     }
     
 }
    return false;
}
if (!complete_migration_check_table_exists(TABLE_PREFIX . "processed_objects", DB::connection()->getLink())) {
    DB::execute("CREATE TABLE `" . TABLE_PREFIX . "processed_objects` (\r\n\t\t\t\t  `object_id` INTEGER UNSIGNED,\r\n\t\t\t\t  PRIMARY KEY (`object_id`)\r\n\t\t\t\t) ENGINE = InnoDB;");
}
try {
    $sql = "";
    $first_row = true;
    $cant = 0;
    $count = 0;
    $processed_objects = array();
    $user = Contacts::findOne(array("conditions" => "user_type = (SELECT id FROM " . TABLE_PREFIX . "permission_groups WHERE name='Super Administrator')"));
    $object_controller = new ObjectController();
    $objects = Objects::findAll(array('id' => true, "conditions" => "id NOT IN(SELECT object_id FROM " . TABLE_PREFIX . "processed_objects)", "order" => "id DESC", "limit" => OBJECT_COUNT));
    foreach ($objects as $obj) {
        $cobj = Objects::findObject($obj);
        if ($cobj instanceof ContentDataObject) {
            if (!$cobj instanceof Workspace) {
                $mem_ids = $cobj->getMemberIds();
                if (count($mem_ids) > 0) {
                    $object_controller->add_to_members($cobj, $mem_ids, $user);
                } else {
                    $cobj->addToSharingTable();
                }
                $cobj->addToSearchableObjects(true);
            }
            // add mails to sharing table for account owners
            if ($cobj instanceof MailContent && $cobj->getAccount() instanceof MailAccount) {
                $db_result = DB::execute("SELECT contact_id FROM " . TABLE_PREFIX . "mail_account_contacts WHERE account_id = " . $cobj->getAccountId());
                $macs = $db_result->fetchAll();
                if ($macs && is_array($macs) && count($macs) > 0) {
Exemple #26
0
    } else {
        add_page_action(lang('unarchive'), "javascript:if(confirm('" . lang('confirm unarchive member', $ot_name) . "')) og.openLink('" . get_url('member', 'unarchive', array('id' => $member->getId())) . "');", 'ico-unarchive-obj');
    }
    $delete_url = get_url('member', 'delete', array('id' => $member->getId(), 'start' => true));
    add_page_action(lang('delete'), "javascript:og.deleteMember('" . $delete_url . "','" . $ot_name . "');", 'ico-delete');
}
$form_title = $object_type_name ? ($member->isNew() ? lang('new') : lang('edit')) . strtolower(" {$object_type_name}") : lang('new member');
$new_member_text = $object_type_name ? ($member->isNew() ? lang('add') : lang('edit')) . strtolower(" {$object_type_name}") : lang('new member');
$categories = array();
Hook::fire('member_edit_categories', array('member' => $member, 'genid' => $genid), $categories);
$has_custom_properties = count(MemberCustomProperties::getCustomPropertyIdsByObjectType($obj_type_sel)) > 0;
$member_ot = ObjectTypes::findById($member->getObjectTypeId());
$dim_obj = null;
if ($member_ot->getType() == 'dimension_object') {
    if (!$member->isNew()) {
        $dim_obj = Objects::findObject($member->getObjectId());
    } else {
        if (class_exists($member_ot->getHandlerClass())) {
            eval('$ot_manager = ' . $member_ot->getHandlerClass() . '::instance();');
            if (isset($ot_manager) && $ot_manager instanceof ContentDataObjects) {
                eval('$dim_obj = new ' . $ot_manager->getItemClass() . '();');
                if ($dim_obj instanceof ContentDataObject) {
                    $dim_obj->setNew(true);
                    $dim_obj->setObjectTypeId($member->getObjectTypeId());
                }
            }
        }
    }
}
?>
<?php

chdir(dirname(__FILE__));
header("Content-type: text/plain");
define("CONSOLE_MODE", true);
include "init.php";
Env::useHelper('format');
define('SCRIPT_MEMORY_LIMIT', 1024 * 1024 * 1024);
// 1 GB
@set_time_limit(0);
ini_set('memory_limit', SCRIPT_MEMORY_LIMIT / (1024 * 1024) + 50 . 'M');
$i = 0;
$objects_ids = Objects::instance()->findAll(array('columns' => array('id'), 'id' => true));
//,'conditions' => 'object_type_id = 6'
echo "\nObjects to process: " . count($objects_ids) . "\n-----------------------------------------------------------------";
foreach ($objects_ids as $object_id) {
    $object = Objects::findObject($object_id);
    $i++;
    if ($object instanceof ContentDataObject) {
        $members = $object->getMembers();
        DB::execute("DELETE FROM " . TABLE_PREFIX . "object_members WHERE object_id = " . $object->getId() . " AND is_optimization = 1;");
        ObjectMembers::addObjectToMembers($object->getId(), $members);
    } else {
        //
    }
    if ($i % 100 == 0) {
        echo "\n{$i} objects processed. Mem usage: " . format_filesize(memory_get_usage(true));
    }
}
 /**
  * quick_add_multiple_files
  * Use this function to upload multiple files
  * @access public
  * @param null
  */
 function quick_add_multiple_files()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $file_data = array_var($_POST, 'file');
     $file = new ProjectFile();
     tpl_assign('file', $file);
     tpl_assign('file_data', $file_data);
     tpl_assign('genid', array_var($_GET, 'genid'));
     tpl_assign('object_id', array_var($_GET, 'object_id'));
     tpl_assign('composing_mail', array_var($_GET, 'composing_mail'));
     if (is_array(array_var($_POST, 'file'))) {
         //$this->setLayout("html");
         $upload_option = array_var($file_data, 'upload_option', -1);
         try {
             //members
             $member_ids = array();
             $object_controller = new ObjectController();
             if (count(active_context_members(false)) > 0) {
                 $member_ids = active_context_members(false);
             } elseif (array_var($file_data, 'member_ids')) {
                 $member_ids = explode(',', array_var($file_data, 'member_ids'));
                 if (is_numeric($member_ids) && $member_ids > 0) {
                     $member_ids = array($member_ids);
                 }
             } elseif (array_var($file_data, 'object_id')) {
                 $object = Objects::findObject(array_var($file_data, 'object_id'));
                 if ($object instanceof ContentDataObject) {
                     $member_ids = $object->getMemberIds();
                 } else {
                     // add only to logged_user's person member
                 }
             } else {
                 // add only to logged_user's person member
             }
             $upload_id = array_var($file_data, 'upload_id');
             $uploaded_file = array_var($_SESSION, $upload_id, array());
             //files ids to return
             $file_ids = array();
             if (isset($uploaded_file['name']) && is_array($uploaded_file['name'])) {
                 foreach ($uploaded_file['name'] as $key => $file_name) {
                     if (count($uploaded_file['name']) == 1 && array_var($file_data, 'name') != "" && array_var($file_data, 'name') != $file_name) {
                         $file_name = array_var($file_data, 'name');
                     }
                     $file_data_mult = $file_data;
                     $file_data_mult['name'] = $file_name;
                     $uploaded_file_mult['name'] = $file_name;
                     $uploaded_file_mult['size'] = $uploaded_file['size'][$key];
                     $uploaded_file_mult['type'] = $uploaded_file['type'][$key];
                     $uploaded_file_mult['tmp_name'] = $uploaded_file['tmp_name'][$key];
                     $uploaded_file_mult['error'] = $uploaded_file['error'][$key];
                     if (count($uploaded_file['name']) != 1) {
                         $upload_option = -1;
                     }
                     $file_ids[] = $this->add_file_from_multi($file_data_mult, $uploaded_file_mult, $member_ids, $upload_option);
                 }
             }
             unset($_SESSION[$upload_id]);
             //data to return
             $files_data_to_return = array();
             foreach ($file_ids as $file_id) {
                 $file_to_ret = ProjectFiles::findById($file_id);
                 if (!$file_to_ret instanceof ProjectFile) {
                     continue;
                 }
                 $file_data = array();
                 $file_data["file_id"] = $file_to_ret->getId();
                 $file_data["file_name"] = $file_to_ret->getFilename();
                 $file_data["icocls"] = 'ico-file ico-' . str_replace(".", "_", str_replace("/", "-", $file_to_ret->getTypeString()));
                 $files_data_to_return[] = $file_data;
             }
             ajx_extra_data(array("files_data" => $files_data_to_return));
             ajx_current("empty");
         } catch (Exception $e) {
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
 /**
  * Add comment
  *
  * Through this controller only logged users can post (no anonymous comments here)
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->setTemplate('add_comment');
     $object_id = get_id('object_id');
     $object = Objects::findObject($object_id);
     if (!$object instanceof ContentDataObject) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $comment = new Comment();
     $comment_data = array_var($_POST, 'comment');
     tpl_assign('comment_form_object', $object);
     tpl_assign('comment', $comment);
     tpl_assign('comment_data', $comment_data);
     if (is_array($comment_data)) {
         try {
             try {
                 $attached_files = ProjectFiles::handleHelperUploads(active_context());
             } catch (Exception $e) {
                 $attached_files = null;
             }
             // try
             $comment->setFromAttributes($comment_data);
             $comment->setRelObjectId($object_id);
             $comment->setObjectName(substr_utf($comment->getText(), 0, 250));
             DB::beginWork();
             $comment->save();
             $comment->addToMembers($object->getMembers());
             if (is_array($attached_files)) {
                 foreach ($attached_files as $attached_file) {
                     $comment->attachFile($attached_file);
                 }
                 // foreach
             }
             // if
             // Subscribe user to object
             if (!$object->isSubscriber(logged_user())) {
                 $object->subscribeUser(logged_user());
             }
             // if
             if (strlen($comment->getText()) < 100) {
                 $comment_head = $comment->getText();
             } else {
                 $lastpos = strpos($comment->getText(), " ", 100);
                 if ($lastpos === false) {
                     $comment_head = $comment->getText();
                 } else {
                     $comment_head = substr($comment->getText(), 0, $lastpos) . "...";
                 }
             }
             $comment_head = html_to_text($comment_head);
             ApplicationLogs::createLog($comment, ApplicationLogs::ACTION_COMMENT, false, false, true, $comment_head);
             DB::commit();
             flash_success(lang('success add comment'));
             ajx_current("reload");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }
 /**
  * Return object connected with this action
  *
  * @access public
  * @param void
  * @return ApplicationDataObject
  */
 function getObject()
 {
     return Objects::findObject($this->getRelObjectId());
 }