Пример #1
0
 function ExecuteQuery()
 {
     $this->data = array();
     $queries = ObjectController::getDashboardObjectQueries(active_project(), null, true);
     $query = '';
     foreach ($queries as $k => $q) {
         if (substr($k, -8) == 'Comments') {
             continue;
         }
         if ($query == '') {
             $query = $q;
         } else {
             $query .= " \n union \n" . $q;
         }
     }
     $ret = 0;
     $res = DB::execute($query);
     if (!$res) {
         return $ret;
     }
     $rows = $res->fetchAll();
     if (!$rows) {
         return $ret;
     }
     foreach ($rows as $row) {
         $value = 0;
         if (isset($row['quantity'])) {
             $value = $row['quantity'];
         }
         $this->data['values'][0]['labels'][] = $row['objectName'];
         $this->data['values'][0]['values'][] = $value;
     }
     //foreach
 }
 public static function get()
 {
     if (self::$instance === null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Пример #3
0
 static function getSubscriberComments($workspace = null, $tag = null, $orderBy = 'created_on', $orderDir = "DESC", $start = 0, $limit = 20)
 {
     $oc = new ObjectController();
     $queries = $oc->getDashboardObjectQueries($workspace, $tag, false, false, $orderBy);
     $query = '';
     if (!is_array($queries)) {
         return array();
     }
     foreach ($queries as $name => $q) {
         if (str_ends_with($name, "Comments")) {
             if ($query == '') {
                 $query = $q;
             } else {
                 $query .= " \n UNION \n" . $q;
             }
         }
     }
     $query .= " ORDER BY `order_value` ";
     if ($orderDir != "ASC" && $orderDir != "DESC") {
         $orderDir = "DESC";
     }
     $query .= " " . $orderDir . " ";
     $query .= " LIMIT " . $start . "," . $limit . " ";
     $res = DB::execute($query);
     $comments = array();
     if (!$res) {
         return $comments;
     }
     $rows = $res->fetchAll();
     if (!is_array($rows)) {
         return $comments;
     }
     foreach ($rows as $row) {
         $manager = $row['object_manager_value'];
         $id = $row['oid'];
         if ($id && $manager) {
             $comment = get_object_by_manager_and_id($id, $manager);
             $object = $comment->getObject();
             if ($object instanceof ProjectDataObject && $object->isSubscriber(logged_user())) {
                 $comments[] = $comment;
             }
         }
     }
     return $comments;
 }
Пример #4
0
 public function index()
 {
     if ($tables = array_diff(ObjectController::getTables(), self::getAvalonTables())) {
         foreach ($tables as &$table) {
             $table = '\'' . $table . '\'';
         }
         $tables = DB::select('SHOW TABLE STATUS WHERE Name IN (' . implode(',', $tables) . ')');
         foreach ($tables as &$table) {
             $table->link = URL::action('ImportController@show', $table->Name);
             $table->Data_length = self::formatBytes($table->Data_length);
         }
     }
     return View::make('avalon::import.index', compact('tables'));
 }
 /**
  * Costruttore
  */
 public function __construct(SQLIImportHandlerOptions $options = null)
 {
     $this->curLog = ObjectController::get();
     try {
         parent::__construct($options);
         $this->curLog->ocLoggerUtil->addInfoMessage('---------------------------');
         $this->curLog->ocLoggerUtil->addInfoMessage('ITTematicaSyncHandler - Enter');
         $this->controller = new ITTematicaSyncController($options);
         $this->curLog->ocLoggerUtil->writeLogs();
     } catch (Exception $ex) {
         $this->curLog->ocLoggerUtil->addErrorMessage('Error in ITTematicaSyncHandler - construct: ' . $ex->getMessage());
         $this->curLog->ocLoggerUtil->writeLogs();
         echo 'Got Exception on ITTematicaSyncHandler - initialize: ' . $ex->getMessage() . "\n";
     }
 }
<?php

$ROOT = plugin_dir_path(__FILE__) . "../../plugins/wpcity/";
include_once $ROOT . "controllers/ObjectController.php";
$controller = new ObjectController();
if (isset($_POST["dilo_submit"])) {
    $objekt = $controller->addPublic();
} else {
    $objekt = $controller->getInitPublicForm();
}
get_header();
?>

<div id="page" class="index podnet pridat-dilo">
<div class="inner">
<div class="padding">

<h2>Přidat dílo</h2>

<?php 
include_once $ROOT . "fw/templates/messages.php";
?>
    
<p>Děkujeme za váš zájem o projekt Křížky a vetřelci. Za každý nově přidaný bod do mapy budeme rádi. Pro přidání můžete použít 
formulář níže nebo vše poslat na e-mail <a href="mailto:krizkyavetrelci@email.cz">krizkyavetrelci@email.cz</a>. </p>

<p>Budeme rádi za každou novou informaci či fotografii. U fotografií prosím respektujte autorský zákon a přidávejte jen fotografie, které jsou 
vaše vlastní či ke kterým vlastníte autorská práva. Pokud nebude domluveno jinak, budou fotografie na webu k dispozici pod
volnou licencí <a href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0</a>.</p>

<form class="rows" method="post" enctype="multipart/form-data">
 /**
  * Edit specific message
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     $this->setTemplate('add_message');
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current('empty');
         return;
     }
     $message = ProjectMessages::findById(get_id());
     if (!$message instanceof ProjectMessage) {
         flash_error(lang('message dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$message->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $message_data = array_var($_POST, 'message');
     if (!is_array($message_data)) {
         $message_data = array('name' => $message->getObjectName(), 'text' => $message->getText(), 'type_content' => $message->getTypeContent());
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
     }
     // if
     tpl_assign('message', $message);
     tpl_assign('message_data', $message_data);
     if (is_array(array_var($_POST, 'message'))) {
         foreach ($message_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         try {
             //MANAGE CONCURRENCE WHILE EDITING
             /* FIXME or REMOVEME
             			$upd = array_var($_POST, 'updatedon');
             			if ($upd && $message->getUpdatedOn()->getTimestamp() > $upd && !array_var($_POST,'merge-changes') == 'true')
             			{
             				ajx_current('empty');
             				evt_add("handle edit concurrence", array(
             					"updatedon" => $message->getUpdatedOn()->getTimestamp(),
             					"genid" => array_var($_POST,'genid')
             				));
             				return;
             			}
             			if (array_var($_POST,'merge-changes') == 'true')
             			{
             				$this->setTemplate('view');
             				$edited_note = ProjectMessages::findById($message->getId());
             				tpl_assign('message', $edited_note);
             				tpl_assign('subscribers', $edited_note->getSubscribers());
             				ajx_extra_data(array("name" => $edited_note->getObjectName(), 'icon'=>'ico-message'));
             				ajx_set_no_toolbar(true);
             				ajx_set_panel(lang ('tab name',array('name'=>$edited_note->getObjectName())));					
             				return;
             			}
             			*/
             if (config_option("wysiwyg_messages")) {
                 $message_data['type_content'] = "html";
                 $message_data['text'] = preg_replace("/[\n|\r|\n\r]/", '', array_var($message_data, 'text'));
             } else {
                 $message_data['type_content'] = "text";
             }
             $message->setFromAttributes($message_data);
             DB::beginWork();
             $message->save();
             $object_controller = new ObjectController();
             $member_ids = json_decode(array_var($_POST, 'members'));
             $object_controller->add_to_members($message, $member_ids);
             $object_controller->link_to_new_object($message);
             $object_controller->add_subscribers($message);
             $object_controller->add_custom_properties($message);
             $message->resetIsRead();
             DB::commit();
             ApplicationLogs::createLog($message, ApplicationLogs::ACTION_EDIT);
             flash_success(lang('success edit message', $message->getObjectName()));
             if (array_var($_POST, 'popup', false)) {
                 ajx_current("reload");
             } else {
                 ajx_current("back");
             }
             if (array_var($_REQUEST, 'modal')) {
                 evt_add("reload current panel");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Пример #8
0
        function repetitive_event_related_edit($event,$data){
            // run the query to set the event data
            $event->setFromAttributes($data);

            $this->registerInvitations($data, $event, false);
            if (isset($data['confirmAttendance'])) {
                $this->change_invitation_state($data['confirmAttendance'], $event->getId(), $user_filter);
            }
            DB::beginWork();
            $event->save();  

            if($event->getSpecialID() != ""){
                $this->sync_calendar_extern($event);
            }

            $object_controller = new ObjectController();
            $object_controller->add_to_members($event, array_var($task_data, 'members'));
            $object_controller->add_subscribers($event);

            $object_controller->link_to_new_object($event);
            $object_controller->add_custom_properties($event);
            $object_controller->add_reminders($event);

            $event->resetIsRead();

            ApplicationLogs::createLog($event, ApplicationLogs::ACTION_EDIT);
        }
 static function getLastActivities($project, $tag, $quantity)
 {
     $conditions = "";
     $object_ids = array();
     $queries = ObjectController::getDashboardObjectQueries($project, $tag, false, 'all', null, 'updatedOn', '', 'all');
     $query = '';
     foreach ($queries as $q) {
         $res = DB::execute($q);
         if (!$res) {
             continue;
         }
         $rows = $res->fetchAll();
         if (is_array($rows) && count($rows) > 0) {
             $ids = array();
             $manager = "";
             foreach ($rows as $row) {
                 //$ids .= ($ids == "" ? "" : ",") . $row['oid'];
                 $ids[] = $row['oid'];
                 $manager = $row['object_manager_value'];
             }
             if (isset($object_ids[$manager])) {
                 $object_ids[$manager] = array_merge($object_ids[$manager], $ids);
             } else {
                 $object_ids[$manager] = $ids;
             }
         }
     }
     foreach ($object_ids as $manager => $ids) {
         $ids_str = implode(",", $ids);
         $extra_cond = $manager == 'MailContents' ? "AND `action` <> 'add'" : "";
         $conditions .= ($conditions == "" ? "" : " OR ") . "(`rel_object_manager` = '{$manager}' AND `rel_object_id` IN ({$ids_str}) {$extra_cond})";
     }
     // Show user activity only in root ws
     if (logged_user()->isAdministrator() && $project == null) {
         $conditions .= ($conditions == "" ? "" : " OR ") . "`rel_object_manager` = 'Users'";
     }
     if ($project instanceof Project) {
         $project_ids = $project->getAllSubWorkspacesCSV(true, logged_user());
     } else {
         $project_ids = logged_user()->getActiveProjectIdsCSV();
     }
     $conditions .= ($conditions == "" ? "" : " OR ") . "(`rel_object_manager` = 'Projects' AND `rel_object_id` IN ({$project_ids}))";
     return self::findAll(array('conditions' => $conditions, 'order' => '`created_on` DESC', 'limit' => $quantity));
 }
 /**
  * Copies tasks from milestoneFrom to milestoneTo.
  *
  * @param ProjectMilestone $milestoneFrom
  * @param ProjectMilestone $milestoneTo
  */
 function copyTasks(ProjectMilestone $milestoneFrom, ProjectMilestone $milestoneTo, $as_template = false)
 {
     //FIXME
     foreach ($milestoneFrom->getTasks($as_template) as $sub) {
         if ($sub->getParentId() != 0) {
             continue;
         }
         $new = ProjectTasks::createTaskCopy($sub);
         $new->setMilestoneId($milestoneTo->getId());
         $new->save();
         $object_controller = new ObjectController();
         $members = $milestoneFrom->getMemberIds();
         if (count($members)) {
             $object_controller->add_to_members($new, $members);
         }
         /*
         			foreach ($sub->getWorkspaces() as $workspace) {
         				if (ProjectTask::canAdd(logged_user(), $workspace)) {
         					$new->addToWorkspace($workspace);
         				}
         			}
         
         			if (!$as_template && active_project() instanceof Project && ProjectTask::canAdd(logged_user(), active_project())) {
         				$new->removeFromAllWorkspaces();
         				$new->addToWorkspace(active_project());
         			}
         */
         $new->copyCustomPropertiesFrom($sub);
         $new->copyLinkedObjectsFrom($sub);
         ProjectTasks::copySubTasks($sub, $new, $as_template);
     }
 }
Пример #11
0
 /**
  * Edit logged user profile. 
  * Called with different POST format from "administration/users/edit user profile " and from "profile/edit my profile" 
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_profile()
 {
     ajx_set_panel("");
     $user = Contacts::findById(get_id());
     if (!($user instanceof Contact && $user->isUser()) || $user->getDisabled()) {
         flash_error(lang('user dnx'));
         ajx_current("empty");
         return;
     }
     // if
     $company = $user->getCompany();
     /*if(!($company instanceof Contact)) {
     			flash_error(lang('company dnx'));
     			ajx_current("empty");
     			return;
     		} // if
     		*/
     if (!$user->canUpdateProfile(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUserUrl();
     }
     // if
     tpl_assign('redirect_to', null);
     $user_data = array_var($_POST, 'user');
     if (!is_array($user_data)) {
         $user_data = array('username' => $user->getUsername(), 'email' => $user->getEmailAddress(), 'display_name' => $user->getObjectName(), 'timezone' => $user->getTimezone(), 'company_id' => $user->getCompanyId(), 'is_admin' => $user->isAdministrator(), 'type' => $user->getUserType());
         // array
     }
     // if
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('user_data', $user_data);
     tpl_assign('billing_categories', BillingCategories::findAll());
     // Permission Groups
     $groups = PermissionGroups::getNonPersonalSameLevelPermissionsGroups('`parent_id`,`id` ASC');
     tpl_assign('groups', $groups);
     $roles = SystemPermissions::getAllRolesPermissions();
     tpl_assign('roles', $roles);
     $tabs = TabPanelPermissions::getAllRolesModules();
     tpl_assign('tabs_allowed', $tabs);
     // Submit user
     if (is_array(array_var($_POST, 'user'))) {
         $company_id = array_var($user_data, 'company_id');
         if ($company_id && !Contacts::findById($company_id) instanceof Contact) {
             ajx_current("empty");
             flash_error(lang("company dnx"));
             return;
         }
         try {
             DB::beginWork();
             $user->setUserType(array_var($user_data, 'type'));
             $user->setTimezone(array_var($user_data, 'timezone'));
             $user->setDefaultBillingId(array_var($user_data, 'default_billing_id'));
             $user->setUpdatedOn(DateTimeValueLib::now());
             if (logged_user()->isAdministrator()) {
                 //if ($user->getId() != 2) { // System admin cannot change it's company (from Feng 2.0 onwards administrador has id = 2)
                 //	$user->setCompanyId(array_var($user_data,'company_id'));
                 //}
                 $user->setUsername(array_var($user_data, 'username'));
             } else {
                 $user->setCompanyId(array_var($user_data, 'company_id'));
             }
             if (!isset($_POST['sys_perm'])) {
                 $rol_permissions = SystemPermissions::getRolePermissions(array_var($user_data, 'type'));
                 $_POST['sys_perm'] = array();
                 $not_rol_permissions = SystemPermissions::getNotRolePermissions(array_var($user_data, 'type'));
                 foreach ($not_rol_permissions as $npr) {
                     $_POST['sys_perm'][$npr] = 0;
                 }
                 foreach ($rol_permissions as $pr) {
                     $_POST['sys_perm'][$pr] = 1;
                 }
             }
             if (!isset($_POST['mod_perm'])) {
                 $tabs_permissions = TabPanelPermissions::getRoleModules(array_var($user_data, 'type'));
                 $_POST['mod_perm'] = array();
                 foreach ($tabs_permissions as $pr) {
                     $_POST['mod_perm'][$pr] = 1;
                 }
             }
             $user->save();
             $autotimezone = array_var($user_data, 'autodetect_time_zone', null);
             if ($autotimezone !== null) {
                 set_user_config_option('autodetect_time_zone', $autotimezone, $user->getId());
             }
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($user);
             $ret = null;
             Hook::fire('after_edit_profile', $user, $ret);
             $pg_id = $user->getPermissionGroupId();
             save_permissions($pg_id, $user->isGuest());
             DB::commit();
             flash_success(lang('success update profile'));
             ajx_current("back");
             ajx_add("overview-panel", "reload");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }
 function list_all()
 {
     ajx_current("empty");
     $project = active_project();
     $isProjectView = $project instanceof Project;
     $start = array_var($_GET, 'start');
     $limit = array_var($_GET, 'limit');
     if (!$start) {
         $start = 0;
     }
     if (!$limit) {
         $limit = config_option('files_per_page');
     }
     $order = array_var($_GET, 'sort');
     $orderdir = array_var($_GET, 'dir');
     $tag = array_var($_GET, 'tag');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'charts'));
         list($succ, $err) = ObjectController::do_delete_objects($ids, 'ProjectCharts');
         if ($err > 0) {
             flash_error(lang('error delete objects', $err));
         } else {
             flash_success(lang('success delete objects', $succ));
         }
     } else {
         if (array_var($_GET, 'action') == 'tag') {
             $ids = explode(',', array_var($_GET, 'charts'));
             $tagTag = array_var($_GET, 'tagTag');
             list($succ, $err) = ObjectController::do_tag_object($tagTag, $ids, 'ProjectCharts');
             if ($err > 0) {
                 flash_error(lang('error tag objects', $err));
             } else {
                 flash_success(lang('success tag objects', $succ));
             }
         }
     }
     if ($page < 0) {
         $page = 1;
     }
     //$conditions = logged_user()->isMemberOfOwnerCompany() ? '' : ' `is_private` = 0';
     if ($tag == '' || $tag == null) {
         $tagstr = " 1=1";
         // dummy condition
     } else {
         $tagstr = "(select count(*) from " . TABLE_PREFIX . "tags where " . TABLE_PREFIX . "project_charts.id = " . TABLE_PREFIX . "tags.rel_object_id and " . TABLE_PREFIX . "tags.tag = '" . $tag . "' and " . TABLE_PREFIX . "tags.rel_object_manager ='ProjectCharts' ) > 0 ";
     }
     /* TODO: handle with permissions_sql_for_listings */
     //$permission_str = ' AND (' . permissions_sql_for_listings(ProjectCharts::instance(), ACCESS_LEVEL_READ, logged_user()) . ')';
     $permission_str = " AND " . ProjectCharts::getWorkspaceString(logged_user()->getWorkspacesQuery(true));
     if ($isProjectView) {
         $pids = $project->getAllSubWorkspacesQuery(true);
         $project_str = " AND " . ProjectCharts::getWorkspaceString($pids);
     } else {
         $project_str = "";
     }
     list($charts, $pagination) = ProjectCharts::paginate(array("conditions" => '`trashed_by_id` = 0 AND `archived_by_id` = 0 AND ' . $tagstr . $permission_str . $project_str, 'order' => '`title` ASC'), config_option('files_per_page', 10), $page);
     // paginate
     tpl_assign('totalCount', $pagination->getTotalItems());
     tpl_assign('charts', $charts);
     tpl_assign('pagination', $pagination);
     tpl_assign('tags', Tags::getTagNames());
     $object = array("totalCount" => $pagination->getTotalItems(), "charts" => array());
     $factory = new ProjectChartFactory();
     $types = $factory->getChartDisplays();
     if (isset($charts)) {
         foreach ($charts as $c) {
             if ($c->getProject() instanceof Project) {
                 $tags = project_object_tags($c);
             } else {
                 $tags = "";
             }
             $object["charts"][] = array("id" => $c->getId(), "name" => $c->getTitle(), "type" => $types[$c->getDisplayId()], "tags" => $tags, "project" => $c->getProject() ? $c->getProject()->getName() : '', "projectId" => $c->getProjectId());
         }
     }
     ajx_extra_data($object);
     tpl_assign("listing", $object);
 }
            return true;
        }
    }
    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) {
Пример #14
0
 /**
  * Edit specific webpage
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add');
     $webpage = ProjectWebpages::findById(get_id());
     if (!$webpage instanceof ProjectWebpage) {
         flash_error(lang('webpage dnx'));
         ajx_current("empty");
         return;
     }
     if (!$webpage->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $webpage_data = array_var($_POST, 'webpage');
     if (!is_array($webpage_data)) {
         $webpage_data = array('url' => $webpage->getUrl(), 'name' => $webpage->getObjectName(), 'description' => $webpage->getDescription());
     }
     if (is_array(array_var($_POST, 'webpage'))) {
         try {
             $webpage->setFromAttributes($webpage_data);
             DB::beginWork();
             $webpage->save();
             $member_ids = json_decode(array_var($_POST, 'members'));
             $object_controller = new ObjectController();
             $object_controller->add_to_members($webpage, $member_ids);
             $object_controller->link_to_new_object($webpage);
             $object_controller->add_subscribers($webpage);
             $object_controller->add_custom_properties($webpage);
             ApplicationLogs::createLog($webpage, ApplicationLogs::ACTION_EDIT);
             $webpage->resetIsRead();
             DB::commit();
             flash_success(lang('success edit webpage', $webpage->getObjectName()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
     }
     tpl_assign('webpage', $webpage);
     tpl_assign('webpage_data', $webpage_data);
 }
Пример #15
0
 private function save_object($request)
 {
     $response = false;
     if (!empty($request['args'])) {
         $service = $request['srv'];
         switch ($service) {
             case "task":
                 if ($request['args']['id']) {
                     $object = ProjectTasks::instance()->findByid($request['args']['id']);
                 } else {
                     $object = new ProjectTask();
                 }
                 if ($object instanceof ProjectTask) {
                     if (!empty($request['args']['title'])) {
                         $object->setObjectName($request['args']['title']);
                     }
                     if (!empty($request['args']['description'])) {
                         $object->setText($request['args']['description']);
                     }
                     if (!empty($request['args']['due_date'])) {
                         if ($request['args']['due_date'] != '' && $request['args']['due_date'] != date_format_tip('dd/mm/yyyy')) {
                             $date_format = 'dd/mm/yyyy';
                             $object->setDueDate(DateTimeValueLib::dateFromFormatAndString($date_format, $value));
                         }
                     }
                     if (!empty($request['args']['completed'])) {
                         $object->setPercentCompleted($request['args']['completed']);
                     }
                     if (!empty($request['args']['assign_to'])) {
                         $object->setAssignedToContactId($request['args']['assign_to']);
                     }
                     if (!empty($request['args']['priority'])) {
                         $object->setPriority($request['args']['priority']);
                     }
                 }
                 break;
             case 'note':
                 if ($request['args']['id']) {
                     $object = ProjectMessages::instance()->findByid($request['args']['id']);
                 } else {
                     $object = new ProjectMessage();
                 }
                 if ($object instanceof ProjectMessage) {
                     if (!empty($request['args']['title'])) {
                         $object->setObjectName($request['args']['title']);
                     }
                     if (!empty($request['args']['title'])) {
                         $object->setText($request['args']['text']);
                     }
                 }
                 break;
         }
         // END SWITCH
         if ($object) {
             try {
                 $context = array();
                 $members = array();
                 if (!empty($request['args']['members'])) {
                     $members = $request['args']['members'];
                     $context = get_context_from_array($members);
                 }
                 //Check permissions:
                 if ($request['args']['id'] && $object->canEdit(logged_user()) || !$request['args']['id'] && $object->canAdd(logged_user(), $context)) {
                     DB::beginWork();
                     $object->save();
                     $object_controller = new ObjectController();
                     if (!$request['args']['id']) {
                         $object_controller->add_to_members($object, $members);
                     }
                     DB::commit();
                     $response = true;
                 }
             } catch (Exception $e) {
                 DB::rollback();
                 return false;
             }
         }
     }
     return $this->response('json', $response);
 }
Пример #16
0
 public function reorder($object_name)
 {
     $fields = explode('&', Input::get('order'));
     $precedence = 1;
     foreach ($fields as $field) {
         list($garbage, $id) = explode('=', $field);
         if (!empty($id)) {
             DB::table(DB_FIELDS)->where('id', $id)->update(['precedence' => $precedence]);
             $precedence++;
         }
     }
     self::organizeTable($object_name);
     ObjectController::saveSchema();
 }
 function edit_custom_report()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $report_id = array_var($_GET, 'id');
     $report = Reports::getReport($report_id);
     if (!$report->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     if (is_array(array_var($_POST, 'report'))) {
         try {
             ajx_current("empty");
             $report_data = array_var($_POST, 'report');
             $member_ids = json_decode(array_var($_POST, 'members'));
             if (!is_array($member_ids) || count($member_ids) == 0) {
                 flash_error(lang('must choose at least one member'));
                 ajx_current("empty");
                 return;
             }
             $members = Members::findAll(array("conditions" => array("`id` IN(?)", $member_ids)));
             DB::beginWork();
             $report->setObjectName($report_data['name']);
             $report->setDescription($report_data['description']);
             $report->setReportObjectTypeId($report_data['report_object_type_id']);
             $report->setOrderBy($report_data['order_by']);
             $report->setIsOrderByAsc($report_data['order_by_asc'] == 'asc');
             $report->save();
             $conditions = array_var($_POST, 'conditions');
             if (!is_array($conditions)) {
                 $conditions = array();
             }
             foreach ($conditions as $condition) {
                 $newCondition = new ReportCondition();
                 if ($condition['id'] > 0) {
                     $newCondition = ReportConditions::getCondition($condition['id']);
                 }
                 if ($condition['deleted'] == "1") {
                     $newCondition->delete();
                     continue;
                 }
                 $newCondition->setReportId($report_id);
                 $custom_prop_id = isset($condition['custom_property_id']) ? $condition['custom_property_id'] : 0;
                 $newCondition->setCustomPropertyId($custom_prop_id);
                 $newCondition->setFieldName($condition['field_name']);
                 $newCondition->setCondition($condition['condition']);
                 if ($condition['field_type'] == 'boolean') {
                     $newCondition->setValue(isset($condition['value']) && $condition['value']);
                 } else {
                     if ($condition['field_type'] == 'date') {
                         if ($condition['value'] == '') {
                             $newCondition->setValue('');
                         } else {
                             $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condition['value']);
                             $newCondition->setValue(date("m/d/Y", $dtFromWidget->getTimestamp()));
                         }
                     } else {
                         $newCondition->setValue(isset($condition['value']) ? $condition['value'] : '');
                     }
                 }
                 $newCondition->setIsParametrizable(isset($condition['is_parametrizable']));
                 $newCondition->save();
             }
             ReportColumns::delete('report_id = ' . $report_id);
             $columns = array_var($_POST, 'columns');
             asort($columns);
             //sort the array by column order
             foreach ($columns as $column => $order) {
                 if ($order > 0) {
                     $newColumn = new ReportColumn();
                     $newColumn->setReportId($report_id);
                     if (is_numeric($column)) {
                         $newColumn->setCustomPropertyId($column);
                     } else {
                         $newColumn->setFieldName($column);
                     }
                     $newColumn->save();
                 }
             }
             $object_controller = new ObjectController();
             $object_controller->add_to_members($report, $member_ids);
             DB::commit();
             flash_success(lang('custom report updated'));
             ajx_current('back');
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     } else {
         $this->setTemplate('add_custom_report');
         tpl_assign('url', get_url('reporting', 'edit_custom_report', array('id' => $report_id)));
         if ($report instanceof Report) {
             tpl_assign('id', $report_id);
             $report_data = array('name' => $report->getObjectName(), 'description' => $report->getDescription(), 'report_object_type_id' => $report->getReportObjectTypeId(), 'order_by' => $report->getOrderBy(), 'order_by_asc' => $report->getIsOrderByAsc());
             tpl_assign('report_data', $report_data);
             $conditions = ReportConditions::getAllReportConditions($report_id);
             tpl_assign('conditions', $conditions);
             $columns = ReportColumns::getAllReportColumns($report_id);
             $colIds = array();
             foreach ($columns as $col) {
                 if ($col->getCustomPropertyId() > 0) {
                     $colIds[] = $col->getCustomPropertyId();
                 } else {
                     $colIds[] = $col->getFieldName();
                 }
             }
             tpl_assign('columns', $colIds);
         }
         $selected_type = $report->getReportObjectTypeId();
         $types = array(array("", lang("select one")));
         $object_types = ObjectTypes::getAvailableObjectTypes();
         foreach ($object_types as $ot) {
             $types[] = array($ot->getId(), lang($ot->getName()));
         }
         tpl_assign('object_types', $types);
         tpl_assign('selected_type', $selected_type);
         tpl_assign('object', $report);
         tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type), true);
     }
 }
 function instantiate($arguments = null)
 {
     $selected_members = array();
     $id = array_var($arguments, 'id', get_id());
     $template = COTemplates::findById($id);
     if (!$template instanceof COTemplate) {
         flash_error(lang("template dnx"));
         ajx_current("empty");
         return;
     }
     $parameters = TemplateParameters::getParametersByTemplate($id);
     $parameterValues = array_var($arguments, 'parameterValues', array_var($_POST, 'parameterValues'));
     if (count($parameters) > 0 && !isset($parameterValues)) {
         ajx_current("back");
         return;
     }
     $instantiation_id = 0;
     if (count($parameters) > 0) {
         $instantiation_id = $this->save_instantiated_parameters($template, $parameters, $parameterValues);
     }
     if (array_var($_POST, 'members') || array_var($arguments, 'members')) {
         $selected_members = array_var($arguments, 'members', json_decode(array_var($_POST, 'members')));
     } else {
         $context = active_context();
         foreach ($context as $selection) {
             if ($selection instanceof Member) {
                 $selected_members[] = $selection->getId();
             }
         }
     }
     if (array_var($_POST, 'additional_member_ids')) {
         $add_mem_ids = explode(',', array_var($_POST, 'additional_member_ids'));
         if (is_array($add_mem_ids)) {
             foreach ($add_mem_ids as $add_mem_id) {
                 if (is_numeric($add_mem_id)) {
                     $selected_members[] = $add_mem_id;
                 }
             }
         }
     }
     $objects = $template->getObjects();
     $controller = new ObjectController();
     if (count($selected_members) > 0) {
         $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')'));
     } else {
         $selected_members_instances = array();
     }
     DB::beginWork();
     $active_context = active_context();
     $copies = array();
     $copiesIds = array();
     $dependencies = array();
     Hook::fire("verify_objects_before_template_instantiation", $template, $objects);
     foreach ($objects as $object) {
         if (!$object instanceof ContentDataObject) {
             continue;
         }
         // copy object
         if ($object instanceof TemplateTask) {
             //dependencies
             $ptasks = ProjectTaskDependencies::getDependenciesForTemplateTask($object->getId());
             if (!empty($ptasks)) {
                 foreach ($ptasks as $d) {
                     $dependencies[] = $d;
                 }
             }
             $copy = $object->copyToProjectTask($instantiation_id);
             //if is subtask
             if ($copy->getParentId() > 0) {
                 foreach ($copies as $c) {
                     if ($c instanceof ProjectTask) {
                         if ($c->getFromTemplateObjectId() == $object->getParentId()) {
                             $copy->setParentId($c->getId());
                         }
                     }
                 }
             }
         } else {
             if ($object instanceof TemplateMilestone) {
                 $copy = $object->copyToProjectMilestone();
             } else {
                 $copy = $object->copy(false);
                 if ($copy->columnExists('from_template_id')) {
                     $copy->setColumnValue('from_template_id', $object->getId());
                 }
             }
         }
         if ($copy->columnExists('is_template')) {
             $copy->setColumnValue('is_template', false);
         }
         $copy->save();
         $copies[] = $copy;
         $copiesIds[$object->getId()] = $copy->getId();
         $ret = null;
         Hook::fire('after_template_object_instantiation', array('template' => $template, 'original' => $object, 'copy' => $copy), $ret);
         /* Set instantiated object members:
          * 		if no member is active then the instantiated object is put in the same members as the original
          * 		if any members are selected then the instantiated object will be put in those members  
          */
         $template_object_members = $object->getMembers();
         $object_members = array();
         if (count($selected_members) == 0) {
             //change members according to context
             foreach ($active_context as $selection) {
                 if ($selection instanceof Member) {
                     // member selected
                     foreach ($template_object_members as $i => $object_member) {
                         if ($object_member instanceof Member && $object_member->getObjectTypeId() == $selection->getObjectTypeId()) {
                             unset($template_object_members[$i]);
                         }
                     }
                     $object_members[] = $selection->getId();
                 }
             }
         } else {
             $object_members = $selected_members;
         }
         foreach ($template_object_members as $object_member) {
             $object_members[] = $object_member->getId();
         }
         $controller->add_to_members($copy, $object_members);
         // set property values as defined in template
         instantiate_template_task_parameters($object, $copy, $parameterValues);
         // subscribe assigned to
         if ($copy instanceof ProjectTask) {
             foreach ($copy->getOpenSubTasks(false) as $m_task) {
                 if ($m_task->getAssignedTo() instanceof Contact) {
                     $m_task->subscribeUser($m_task->getAssignedTo());
                 }
             }
             if ($copy->getAssignedTo() instanceof Contact) {
                 $copy->subscribeUser($copy->getAssignedTo());
             }
         } else {
             if ($copy instanceof ProjectMilestone) {
                 foreach ($copy->getTasks(false) as $m_task) {
                     if ($m_task->getAssignedTo() instanceof Contact) {
                         $m_task->subscribeUser($m_task->getAssignedTo());
                     }
                 }
             }
         }
     }
     foreach ($copies as $c) {
         if ($c instanceof ProjectTask) {
             if ($c->getMilestoneId() > 0) {
                 // find milestone in copies
                 foreach ($copies as $m) {
                     if ($m instanceof ProjectMilestone && $m->getFromTemplateObjectId() == $c->getMilestoneId()) {
                         $c->setMilestoneId($m->getId());
                         $c->save();
                         break;
                     }
                 }
             }
         }
     }
     //copy dependencies
     foreach ($dependencies as $dependencie) {
         if ($dependencie instanceof ProjectTaskDependency) {
             $dep = new ProjectTaskDependency();
             $dep->setPreviousTaskId($copiesIds[$dependencie->getPreviousTaskId()]);
             $dep->setTaskId($copiesIds[$dependencie->getTaskId()]);
             $dep->save();
         }
     }
     DB::commit();
     foreach ($copies as $c) {
         if ($c instanceof ProjectTask) {
             ApplicationLogs::createLog($c, ApplicationLogs::ACTION_ADD);
         }
     }
     if (is_array($parameters) && count($parameters) > 0) {
         ajx_current("back");
     } else {
         ajx_current("back");
     }
 }
Пример #19
0
	/**
	 * Copies subtasks from taskFrom to taskTo.
	 *
	 * @param ProjectTask $taskFrom
	 * @param ProjectTask $taskTo
	 */
	function copySubTasks(ProjectTask $taskFrom, ProjectTask $taskTo, $as_template = false) {
		foreach ( $taskFrom->getSubTasks () as $sub ) {
			if ($sub->getId() == $taskTo->getId()) continue;
			$new = ProjectTasks::createTaskCopy ( $sub );
			$new->setIsTemplate ( $as_template );
			$new->setParentId ( $taskTo->getId () );
			$new->setMilestoneId ( $taskTo->getMilestoneId () );
			$new->setOrder ( ProjectTasks::maxOrder ( $new->getParentId (), $new->getMilestoneId () ) );
			if ($sub->getIsTemplate ()) {
				$new->setFromTemplateId ( $sub->getId () );
			}
			$new->save ();
			
			$object_controller = new ObjectController();
			if (count($taskFrom->getMemberIds())) {
				$object_controller->add_to_members($new, $taskFrom->getMemberIds());
			}
			$new->copyCustomPropertiesFrom ( $sub );
			$new->copyLinkedObjectsFrom ( $sub );
			ProjectTasks::copySubTasks ( $sub, $new, $as_template );
		}
	}
 /**
  * Counts dashboard objects
  *
  * @return unknown
  */
 private function countTasksAndMilestones($tag = null, $project = null)
 {
     $queries = ObjectController::getDashboardObjectQueries($project, $tag, true);
     $query = $queries['ProjectTasks'] . " UNION " . $queries['ProjectMilestones'];
     $ret = 0;
     $res1 = DB::execute($query);
     if ($res1) {
         $rows = $res1->fetchAll();
         if ($rows) {
             foreach ($rows as $row) {
                 if (isset($row['quantity'])) {
                     $ret += $row['quantity'];
                 }
             }
             //foreach
         }
     }
     return $ret;
 }
Пример #21
0
function core_dim_add_new_contact_to_person_dimension($object)
{
    /* @var $object Contact */
    $person_ot = ObjectTypes::findOne(array("conditions" => "`name` = 'person'"));
    $company_ot = ObjectTypes::findOne(array("conditions" => "`name` = 'company'"));
    $person_dim = Dimensions::findOne(array("conditions" => "`code` = 'feng_persons'"));
    if ($person_ot instanceof ObjectType && $person_dim instanceof Dimension) {
        $oid = $object->isCompany() ? $company_ot->getId() : $person_ot->getId();
        $tmp_mem = Members::findOne(array("conditions" => "`dimension_id` = " . $person_dim->getId() . " AND `object_type_id` = {$oid} AND `object_id` = " . $object->getId()));
        $reload_dimension = true;
        if ($tmp_mem instanceof Member) {
            $member = $tmp_mem;
            $reload_dimension = false;
        } else {
            $member = new Member();
            $member->setName($object->getObjectName());
            $member->setDimensionId($person_dim->getId());
            $parent_member_id = 0;
            $depth = 1;
            if ($object->isCompany()) {
                $member->setObjectTypeId($company_ot->getId());
            } else {
                $member->setObjectTypeId($person_ot->getId());
                if ($object->getCompanyId() > 0) {
                    $pmember = Members::findOne(array('conditions' => '`object_id` = ' . $object->getCompanyId() . ' AND `object_type_id` = ' . $company_ot->getId() . ' AND `dimension_id` = ' . $person_dim->getId()));
                    if ($pmember instanceof Member) {
                        $parent_member_id = $pmember->getId();
                        $depth = $pmember->getDepth() + 1;
                    }
                }
            }
            $member->setParentMemberId($parent_member_id);
            $member->setDepth($depth);
            $member->setObjectId($object->getId());
            $member->save();
        }
        $sql = "INSERT INTO `" . TABLE_PREFIX . "contact_dimension_permissions` (`permission_group_id`, `dimension_id`, `permission_type`)\n\t\t\t\t SELECT `c`.`permission_group_id`, " . $person_dim->getId() . ", 'check'\n\t\t\t\t FROM `" . TABLE_PREFIX . "contacts` `c` \n\t\t\t\t WHERE `c`.`is_company`=0 AND `c`.`user_type`!=0 AND `c`.`disabled`=0 AND `c`.`object_id`=" . $object->getId() . "\n\t\t\t\t ON DUPLICATE KEY UPDATE `dimension_id`=`dimension_id`;";
        DB::execute($sql);
        $sql = "INSERT INTO `" . TABLE_PREFIX . "contact_member_permissions` (`permission_group_id`, `member_id`, `object_type_id`, `can_write`, `can_delete`)\n\t\t\t\t SELECT `c`.`permission_group_id`, " . $member->getId() . ", `ot`.`id`, (`c`.`object_id` = " . $object->getId() . ") as `can_write`, (`c`.`object_id` = " . $object->getId() . ") as `can_delete`\n\t\t\t\t FROM `" . TABLE_PREFIX . "contacts` `c` JOIN `" . TABLE_PREFIX . "object_types` `ot` \n\t\t\t\t WHERE `c`.`is_company`=0 AND `c`.`object_id`=" . $object->getId() . "\n\t\t\t\t \tAND `c`.`user_type`!=0 AND `c`.`disabled`=0\n\t\t\t\t\tAND `ot`.`type` IN ('content_object', 'comment')\n\t\t\t\t ON DUPLICATE KEY UPDATE `member_id`=`member_id`;";
        DB::execute($sql);
        DB::execute("DELETE FROM `" . TABLE_PREFIX . "contact_member_permissions` WHERE `permission_group_id` = 0;");
        // NEW! Add contact to its own member to be searchable
        if (logged_user() instanceof Contact) {
            $ctrl = new ObjectController();
            $ctrl->add_to_members($object, array($member->getId()));
        } else {
            $object->addToMembers(array($member));
            $object->addToSharingTable();
        }
        // add permission to creator
        if ($object->getCreatedBy() instanceof Contact) {
            DB::execute("INSERT INTO `" . TABLE_PREFIX . "contact_member_permissions` (`permission_group_id`, `member_id`, `object_type_id`, `can_write`, `can_delete`)\n\t\t\t\t SELECT " . $object->getCreatedBy()->getPermissionGroupId() . ", " . $member->getId() . ", `ot`.`id`, 1, 1\n\t\t\t\t FROM `" . TABLE_PREFIX . "object_types` `ot` \n\t\t\t\t WHERE `ot`.`type` IN ('content_object', 'comment')\n\t\t\t\t ON DUPLICATE KEY UPDATE `member_id`=`member_id`;");
        }
        if ($reload_dimension) {
            evt_add("reload dimension tree", $member->getDimensionId());
        }
    }
}
 /**
  * Show and process edit milestone form
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_milestone');
     $milestone = ProjectMilestones::findById(get_id());
     if (!$milestone instanceof ProjectMilestone) {
         flash_error(lang('milestone dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$milestone->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $milestone_data = array_var($_POST, 'milestone');
     if (!is_array($milestone_data)) {
         $tag_names = $milestone->getTagNames();
         $milestone_data = array('name' => $milestone->getName(), 'due_date' => $milestone->getDueDate(), 'description' => $milestone->getDescription(), 'assigned_to' => $milestone->getAssignedToCompanyId() . ':' . $milestone->getAssignedToUserId(), 'tags' => is_array($tag_names) ? implode(', ', $tag_names) : '', 'is_private' => $milestone->isPrivate(), 'is_urgent' => $milestone->getIsUrgent());
         // array
     }
     // if
     tpl_assign('milestone_data', $milestone_data);
     tpl_assign('milestone', $milestone);
     if (is_array(array_var($_POST, 'milestone'))) {
         if (array_var($milestone_data, 'due_date_value') != '') {
             $milestone_data['due_date'] = getDateValue(array_var($milestone_data, 'due_date_value'));
         } else {
             $now = DateTimeValueLib::now();
             $milestone_data['due_date'] = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), $now->getDay(), $now->getYear());
         }
         $old_owner = $milestone->getAssignedTo();
         // remember the old owner
         $assigned_to = explode(':', array_var($milestone_data, 'assigned_to', ''));
         $old_is_private = $milestone->isPrivate();
         $milestone->setFromAttributes($milestone_data);
         $urgent = array_var($milestone_data, 'is_urgent') == 'checked';
         $milestone->setIsUrgent($urgent);
         if (!logged_user()->isMemberOfOwnerCompany()) {
             $milestone->setIsPrivate($old_is_private);
         }
         $old_project_id = $milestone->getProjectId();
         $project_id = array_var($_POST, 'ws_ids');
         if ($old_project_id != $project_id) {
             $newProject = Projects::findById($project_id);
             if (!$milestone->canAdd(logged_user(), $newProject)) {
                 flash_error(lang('no access permissions'));
                 ajx_current("empty");
                 return;
             }
             // if
             $milestone->move_inconsistent_tasks($newProject);
         }
         $milestone->setAssignedToCompanyId(array_var($assigned_to, 0, 0));
         $milestone->setAssignedToUserId(array_var($assigned_to, 1, 0));
         try {
             DB::beginWork();
             $milestone->save();
             $milestone->setTagsFromCSV(array_var($milestone_data, 'tags'));
             $object_controller = new ObjectController();
             $object_controller->add_to_workspaces($milestone);
             $object_controller->link_to_new_object($milestone);
             $object_controller->add_subscribers($milestone);
             $object_controller->add_custom_properties($milestone);
             $object_controller->add_reminders($milestone);
             ApplicationLogs::createLog($milestone, $milestone->getWorkspaces(), ApplicationLogs::ACTION_EDIT);
             DB::commit();
             // If owner is changed send notification but don't break submission
             try {
                 $new_owner = $milestone->getAssignedTo();
                 if (array_var($milestone_data, 'send_notification') == 'checked') {
                     if ($old_owner instanceof User) {
                         // We have a new owner and it is different than old owner
                         if ($new_owner instanceof User && $new_owner->getId() != $old_owner->getId()) {
                             Notifier::milestoneAssigned($milestone);
                         }
                     } else {
                         // We have new owner
                         if ($new_owner instanceof User) {
                             Notifier::milestoneAssigned($milestone);
                         }
                     }
                     // if
                 }
                 // if
             } catch (Exception $e) {
             }
             // try
             flash_success(lang('success edit milestone', $milestone->getName()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Пример #23
0
 function repetitive_task_related_edit($task, $task_data)
 {
     $was_template = $task->getIsTemplate();
     $task->setFromAttributes($task_data);
     $task->setIsTemplate($was_template);
     // is_template value must not be changed from ui
     $totalMinutes = array_var($task_data, 'time_estimate_hours') * 60 + array_var($task_data, 'time_estimate_minutes');
     $task->setTimeEstimate($totalMinutes);
     if ($task->getParentId() > 0 && $task->hasChild($task->getParentId())) {
         flash_error(lang('task child of child error'));
         ajx_current("empty");
         return;
     }
     DB::beginWork();
     $task->save();
     $task->setObjectName(array_var($task_data, 'name'));
     $task->save();
     // dependencies
     if (config_option('use tasks dependencies')) {
         $previous_tasks = array_var($task_data, 'previous');
         if (is_array($previous_tasks)) {
             foreach ($previous_tasks as $ptask) {
                 if ($ptask == $task->getId()) {
                     continue;
                 }
                 $dep = ProjectTaskDependencies::findById(array('previous_task_id' => $ptask, 'task_id' => $task->getId()));
                 if (!$dep instanceof ProjectTaskDependency) {
                     $dep = new ProjectTaskDependency();
                     $dep->setPreviousTaskId($ptask);
                     $dep->setTaskId($task->getId());
                     $dep->save();
                 }
             }
             $saved_ptasks = ProjectTaskDependencies::findAll(array('conditions' => 'task_id = ' . $task->getId()));
             foreach ($saved_ptasks as $pdep) {
                 if (!in_array($pdep->getPreviousTaskId(), $previous_tasks)) {
                     $pdep->delete();
                 }
             }
         } else {
             ProjectTaskDependencies::delete('task_id = ' . $task->getId());
         }
     }
     // Add assigned user to the subscibers list
     if ($task->getAssignedToContactId() > 0 && Contacts::instance()->findById($task->getAssignedToContactId())) {
         if (!isset($_POST['subscribers'])) {
             $_POST['subscribers'] = array();
         }
         $_POST['subscribers']['user_' . $task->getAssignedToContactId()] = 'checked';
     }
     $object_controller = new ObjectController();
     $object_controller->add_to_members($task, array_var($task_data, 'members'));
     $object_controller->add_subscribers($task);
     $object_controller->link_to_new_object($task);
     $object_controller->add_custom_properties($task);
     $object_controller->add_reminders($task);
     // apply values to subtasks
     $assigned_to = $task->getAssignedToContactId();
     $subtasks = $task->getAllSubTasks();
     $milestone_id = $task->getMilestoneId();
     $apply_ms = array_var($task_data, 'apply_milestone_subtasks') == "checked";
     $apply_at = array_var($task_data, 'apply_assignee_subtasks', '') == "checked";
     foreach ($subtasks as $sub) {
         $modified = false;
         if ($apply_at || !($sub->getAssignedToContactId() > 0)) {
             $sub->setAssignedToContactId($assigned_to);
             $modified = true;
         }
         if ($apply_ms) {
             $sub->setMilestoneId($milestone_id);
             $modified = true;
         }
         if ($modified) {
             $sub->save();
         }
     }
     $task->resetIsRead();
     ApplicationLogs::createLog($task, ApplicationLogs::ACTION_EDIT);
     DB::commit();
 }
Пример #24
0
 function instantiate()
 {
     $selected_members = array();
     $id = get_id();
     $template = COTemplates::findById($id);
     if (!$template instanceof COTemplate) {
         flash_error(lang("template dnx"));
         ajx_current("empty");
         return;
     }
     $parameters = TemplateParameters::getParametersByTemplate($id);
     $parameterValues = array_var($_POST, 'parameterValues');
     if (count($parameters) > 0 && !isset($parameterValues)) {
         ajx_current("back");
         return;
     }
     if (array_var($_POST, 'members')) {
         $selected_members = json_decode(array_var($_POST, 'members'));
     } else {
         $context = active_context();
         foreach ($context as $selection) {
             if ($selection instanceof Member) {
                 $selected_members[] = $selection->getId();
             }
         }
     }
     $objects = $template->getObjects();
     $controller = new ObjectController();
     if (count($selected_members > 0)) {
         $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')'));
     } else {
         $selected_members_instances = array();
     }
     DB::beginWork();
     $active_context = active_context();
     foreach ($objects as $object) {
         if (!$object instanceof ContentDataObject) {
             continue;
         }
         // copy object
         $copy = $object->copy();
         if ($copy->columnExists('is_template')) {
             $copy->setColumnValue('is_template', false);
         }
         if ($copy instanceof ProjectTask) {
             // don't copy parent task and milestone
             $copy->setMilestoneId(0);
             $copy->setParentId(0);
         }
         $copy->save();
         /*		if (!can_write(logged_user(), $selected_members_instances, $copy->getObjectTypeId()) ) {
         				flash_error(lang('no context permissions to add', $copy instanceof ProjectTask ? lang("tasks") : ($copy instanceof ProjectMilestone ? lang('milestones') : '')));
         				DB::rollback();
         				ajx_current("empty");
         				return;
         			}*/
         // Copy members from origial object, if it doesn't have then use active context members
         /*	$template_object_members = $object->getMemberIds();
         			if (count($template_object_members) == 0) {
         				$object_member_ids = active_context_members(false);
         				if (count($object_member_ids) > 0) {
         					$template_object_members = Members::findAll(array("id" => true, "conditions" => "id IN (".implode(",", $object_member_ids).")"));
         				}
         			}*/
         /* Set instantiated object members:
          * foreach dimension:
          * 		if no member is active then the instantiated object is put in the same members as the original for current dimension
          * 		if a member is selected in current dimension then the instantiated object will be put in that member  
          */
         $template_object_members = $object->getMembers();
         $object_members = array();
         foreach ($active_context as $selection) {
             if ($selection instanceof Member) {
                 // member selected
                 $object_members[] = $selection->getId();
             } else {
                 if ($selection instanceof Dimension) {
                     // no member selected
                     foreach ($template_object_members as $tom) {
                         if ($tom->getDimensionId() == $selection->getId()) {
                             $object_members[] = $tom->getId();
                         }
                     }
                 }
             }
         }
         $controller->add_to_members($copy, $object_members);
         // copy linked objects
         $copy->copyLinkedObjectsFrom($object);
         // copy subtasks if applicable
         if ($copy instanceof ProjectTask) {
             ProjectTasks::copySubTasks($object, $copy, false);
             foreach ($copy->getOpenSubTasks(false) as $m_task) {
                 $controller->add_to_members($m_task, $object_members);
             }
             $manager = $copy->manager();
         } else {
             if ($copy instanceof ProjectMilestone) {
                 ProjectMilestones::copyTasks($object, $copy, false);
                 foreach ($copy->getTasks(false) as $m_task) {
                     $controller->add_to_members($m_task, $object_members);
                 }
                 $manager = $copy->manager();
             }
         }
         // copy custom properties
         $copy->copyCustomPropertiesFrom($object);
         // set property values as defined in template
         $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId());
         foreach ($objProp as $property) {
             $propName = $property->getProperty();
             $value = $property->getValue();
             if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) {
                 if (is_array($parameterValues)) {
                     foreach ($parameterValues as $param => $val) {
                         if (strpos($value, '{' . $param . '}') !== FALSE) {
                             $value = str_replace('{' . $param . '}', $val, $value);
                         }
                     }
                 }
             } else {
                 if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) {
                     $operator = '+';
                     if (strpos($value, '+') === false) {
                         $operator = '-';
                     }
                     $opPos = strpos($value, $operator);
                     if ($opPos !== false) {
                         // Is parametric
                         $dateParam = substr($value, 1, strpos($value, '}') - 1);
                         $date = $parameterValues[$dateParam];
                         $dateUnit = substr($value, strlen($value) - 1);
                         // d, w or m (for days, weeks or months)
                         if ($dateUnit == 'm') {
                             $dateUnit = 'M';
                             // make month unit uppercase to call DateTimeValue::add with correct parameter
                         }
                         $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2);
                         $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date);
                         $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600);
                         // set date to GMT 0
                         $value = $date->add($dateUnit, $dateNum);
                     } else {
                         $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value);
                     }
                 }
             }
             if ($value != '') {
                 if (!$copy->setColumnValue($propName, $value)) {
                     $copy->object->setColumnValue($propName, $value);
                 }
                 $copy->save();
             }
         }
         // subscribe assigned to
         if ($copy instanceof ProjectTask) {
             foreach ($copy->getOpenSubTasks(false) as $m_task) {
                 if ($m_task->getAssignedTo() instanceof Contact) {
                     $m_task->subscribeUser($copy->getAssignedTo());
                 }
             }
             if ($copy->getAssignedTo() instanceof Contact) {
                 $copy->subscribeUser($copy->getAssignedTo());
             }
         } else {
             if ($copy instanceof ProjectMilestone) {
                 foreach ($copy->getTasks(false) as $m_task) {
                     if ($m_task->getAssignedTo() instanceof Contact) {
                         $m_task->subscribeUser($copy->getAssignedTo());
                     }
                 }
             }
         }
         // 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();
         }
     }
     DB::commit();
     if (is_array($parameters) && count($parameters) > 0) {
         ajx_current("back");
     } else {
         if (!$choose_ctx) {
             ajx_current("back");
         } else {
             ajx_current("reload");
         }
     }
 }
 /**
  * Edit project
  *
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_project');
     $project = Projects::findById(get_id());
     if (!$project instanceof Project) {
         flash_error(lang('project dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$project->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $project_data = array_var($_POST, 'project');
     if (!is_array($project_data)) {
         $project_data = array('name' => $project->getName(), 'description' => $project->getDescription(), 'show_description_in_overview' => $project->getShowDescriptionInOverview(), 'color' => 0);
         // array
     }
     // if
     $projects = logged_user()->getActiveProjects();
     tpl_assign('project', $project);
     tpl_assign('projects', $projects);
     tpl_assign('project_data', $project_data);
     tpl_assign('billing_amounts', $project->getBillingAmounts());
     tpl_assign('subject_matter_experts', ProjectContacts::getContactsByProject($project));
     if (is_array(array_var($_POST, 'project'))) {
         if (array_var($project_data, 'parent_id') == $project->getId()) {
             flash_error(lang("workspace own parent error"));
             ajx_current("empty");
             return;
         }
         if (!isset($project_data['parent_id'])) {
             $project_data['parent_id'] = $project->getParentId();
         }
         $project->setFromAttributes($project_data);
         try {
             DB::beginWork();
             if (array_var($project_data, 'parent_id') != $project->getParentId()) {
                 if ($project->getParentWorkspace() instanceof Project && !logged_user()->isProjectUser($project->getParentWorkspace())) {
                     flash_error(lang('no access permissions'));
                     ajx_current("empty");
                     return;
                 }
                 // if
                 $parent = Projects::findById(array_var($project_data, 'parent_id'));
                 if ($parent) {
                     if (!$project->canSetAsParentWorkspace($parent)) {
                         flash_error(lang('error cannot set workspace as parent', $parent->getName()));
                         ajx_current("empty");
                         return;
                     }
                 }
                 $project->setParentWorkspace($parent);
             }
             $project->save();
             /* Billing */
             WorkspaceBillings::clearByProject($project);
             $billings = array_var($project_data, 'billing', null);
             if ($billings) {
                 foreach ($billings as $billing_id => $billing) {
                     if ($billing['update'] && $billing['value'] && $billing['value'] != 0) {
                         $wb = new WorkspaceBilling();
                         $wb->setProjectId($project->getId());
                         $wb->setBillingId($billing_id);
                         $value = $billing['value'];
                         if (strpos($value, ',') && !strpos($value, '.')) {
                             $value = str_replace(',', '.', $value);
                         }
                         $wb->setValue($value);
                         $wb->save();
                     }
                 }
             }
             /* Project contacts */
             if (can_manage_contacts(logged_user())) {
                 ProjectContacts::clearByProject($project);
                 $contacts = array_var($project_data, 'contacts', null);
                 if ($contacts) {
                     foreach ($contacts as $contact_data) {
                         $contact = Contacts::findById($contact_data['contact_id']);
                         if ($contact instanceof Contact) {
                             $pc = new ProjectContact();
                             $pc->setProjectId($project->getId());
                             $pc->setContactId($contact_data['contact_id']);
                             $pc->setRole($contact_data['role']);
                             $pc->save();
                         }
                     }
                 }
             }
             /* <permissions> */
             $permissions = null;
             $permissionsString = array_var($_POST, 'permissions');
             if ($permissionsString && $permissionsString != '') {
                 $permissions = json_decode($permissionsString);
             }
             if (is_array($permissions) && count($permissions) > 0) {
                 //Clear old modified permissions
                 $ids = array();
                 foreach ($permissions as $perm) {
                     $ids[] = $perm->wsid;
                 }
                 ProjectUsers::clearByProject($project, implode(',', $ids));
                 //Add new permissions
                 //TODO - Make batch update of these permissions
                 foreach ($permissions as $perm) {
                     if (ProjectUser::hasAnyPermissions($perm->pr, $perm->pc)) {
                         $relation = new ProjectUser();
                         $relation->setProjectId($project->getId());
                         $relation->setUserId($perm->wsid);
                         $relation->setCheckboxPermissions($perm->pc, $relation->getUserOrGroup()->isGuest() ? false : true);
                         $relation->setRadioPermissions($perm->pr, $relation->getUserOrGroup()->isGuest() ? false : true);
                         $relation->save();
                     }
                     //endif
                     //else if the user has no permissions at all, he is not a project_user. ProjectUser is not created
                 }
                 //end foreach
             }
             // if
             /* </permissions> */
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($project);
             ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_EDIT, false, true);
             DB::commit();
             if (logged_user()->isProjectUser($project)) {
                 $workspace_info = $this->get_workspace_info($project);
                 evt_add("workspace edited", $workspace_info);
             }
             flash_success(lang('success edit project', $project->getName()));
             ajx_current("back");
             return;
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
 /**
  * Add single mail
  *
  * @access public
  * @param void
  * @return null
  */
 function add_mail()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->addHelper('textile');
     $mail_accounts = MailAccounts::getMailAccountsByUser(logged_user());
     if (count($mail_accounts) < 1) {
         flash_error(lang('no mail accounts set'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_mail');
     $mail_data = array_var($_POST, 'mail');
     $isDraft = array_var($mail_data, 'isDraft', '') == 'true' ? true : false;
     $isUpload = array_var($mail_data, 'isUpload', '') == 'true' ? true : false;
     $autosave = array_var($mail_data, 'autosave', '') == 'true';
     $id = array_var($mail_data, 'id');
     $mail = MailContents::findById($id);
     $isNew = false;
     if (!$mail) {
         $isNew = true;
         $mail = new MailContent();
     }
     tpl_assign('mail_to', urldecode(array_var($_GET, 'to')));
     tpl_assign('link_to_objects', array_var($_GET, 'link_to_objects'));
     $def_acc = $this->getDefaultAccountId();
     if ($def_acc > 0) {
         tpl_assign('default_account', $def_acc);
     }
     tpl_assign('mail', $mail);
     tpl_assign('mail_data', $mail_data);
     tpl_assign('mail_accounts', $mail_accounts);
     // Form is submited
     if (is_array($mail_data)) {
         $account = MailAccounts::findById(array_var($mail_data, 'account_id'));
         if (!$account instanceof MailAccount) {
             flash_error(lang('mail account dnx'));
             ajx_current("empty");
             return;
         }
         $accountUser = MailAccountUsers::getByAccountAndUser($account, logged_user());
         if (!$accountUser instanceof MailAccountUser) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         if ($account->getOutgoingTrasnportType() == 'ssl' || $account->getOutgoingTrasnportType() == 'tls') {
             $available_transports = stream_get_transports();
             if (array_search($account->getOutgoingTrasnportType(), $available_transports) === FALSE) {
                 flash_error('The server does not support SSL.');
                 ajx_current("empty");
                 return;
             }
         }
         $cp_errs = $this->checkRequiredCustomPropsBeforeSave(array_var($_POST, 'object_custom_properties', array()));
         if (is_array($cp_errs) && count($cp_errs) > 0) {
             foreach ($cp_errs as $err) {
                 flash_error($err);
             }
             ajx_current("empty");
             return;
         }
         $subject = array_var($mail_data, 'subject');
         $body = array_var($mail_data, 'body');
         if (($pre_body_fname = array_var($mail_data, 'pre_body_fname')) != "") {
             $body = str_replace(lang('content too long not loaded'), '', $body, $count = 1);
             $tmp_filename = ROOT . "/tmp/{$pre_body_fname}";
             if (is_file($tmp_filename)) {
                 $body .= file_get_contents($tmp_filename);
                 if (!$isDraft) {
                     @unlink($tmp_filename);
                 }
             }
         }
         if (array_var($mail_data, 'format') == 'html') {
             $css = "font-family:Arial,Verdana,sans-serif;font-size:12px;color:#222;";
             Hook::fire('email_base_css', null, $css);
             str_replace(array("\r", "\n"), "", $css);
             $body = '<div style="' . $css . '">' . $body . '</div>';
             $body = str_replace('<blockquote>', '<blockquote style="border-left:1px solid #987ADD;padding-left:10px;">', $body);
         }
         $type = 'text/' . array_var($mail_data, 'format');
         $to = trim(array_var($mail_data, 'to'));
         if (str_ends_with($to, ",") || str_ends_with($to, ";")) {
             $to = substr($to, 0, strlen($to) - 1);
         }
         $mail_data['to'] = $to;
         $cc = trim(array_var($mail_data, 'cc'));
         if (str_ends_with($cc, ",") || str_ends_with($cc, ";")) {
             $cc = substr($cc, 0, strlen($cc) - 1);
         }
         $mail_data['cc'] = $cc;
         $bcc = trim(array_var($mail_data, 'bcc'));
         if (str_ends_with($bcc, ",") || str_ends_with($bcc, ";")) {
             $bcc = substr($bcc, 0, strlen($bcc) - 1);
         }
         $mail_data['bcc'] = $bcc;
         if (!$isDraft && trim($to . $cc . $bcc) == '') {
             flash_error(lang('recipient must be specified'));
             ajx_current("empty");
             return;
         }
         $invalid_to = MailUtilities::validate_email_addresses($to);
         if (is_array($invalid_to)) {
             flash_error(lang('error invalid recipients', lang('mail to'), implode(", ", $invalid_to)));
             ajx_current("empty");
             return;
         }
         $invalid_cc = MailUtilities::validate_email_addresses($cc);
         if (is_array($invalid_cc)) {
             flash_error(lang('error invalid recipients', lang('mail CC'), implode(", ", $invalid_cc)));
             ajx_current("empty");
             return;
         }
         $invalid_bcc = MailUtilities::validate_email_addresses($bcc);
         if (is_array($invalid_bcc)) {
             flash_error(lang('error invalid recipients', lang('mail BCC'), implode(", ", $invalid_bcc)));
             ajx_current("empty");
             return;
         }
         $last_mail_in_conversation = array_var($mail_data, 'last_mail_in_conversation');
         $conversation_id = array_var($mail_data, 'conversation_id');
         if ($last_mail_in_conversation && $conversation_id) {
             $new_mail_in_conversation = MailContents::getLastMailIdInConversation($conversation_id, true);
             if ($new_mail_in_conversation != $last_mail_in_conversation) {
                 ajx_current("empty");
                 evt_add("new email in conversation", array('id' => $new_mail_in_conversation, 'genid' => array_var($_POST, 'instanceName')));
                 return;
             }
         }
         $mail->setFromAttributes($mail_data);
         $mail->setTo($to);
         $mail->setCc($cc);
         $mail->setBcc($bcc);
         $mail->setSubject($mail_data['subject']);
         $utils = new MailUtilities();
         // attachment
         $linked_attachments = array();
         $attachments = array();
         $objects = array_var($_POST, 'linked_objects');
         $attach_contents = array_var($_POST, 'attach_contents', array());
         if (is_array($objects)) {
             $err = 0;
             $count = -1;
             foreach ($objects as $objid) {
                 $count++;
                 $split = explode(":", $objid);
                 if (count($split) == 2) {
                     $object = get_object_by_manager_and_id($split[1], $split[0]);
                 } else {
                     if (count($split) == 4) {
                         if ($split[0] == 'FwdMailAttach') {
                             $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . $mail_data['account_id'] . "_FwdMailAttach_" . $split[3];
                             if (is_file($tmp_filename)) {
                                 $attachments[] = array("data" => file_get_contents($tmp_filename), "name" => $split[1], "type" => $split[2]);
                                 continue;
                             }
                         }
                     }
                 }
                 if (!isset($object) || !$object) {
                     flash_error(lang('file dnx'));
                     $err++;
                 } else {
                     if (isset($attach_contents[$count])) {
                         if ($split[0] == 'ProjectFiles') {
                             $file = ProjectFiles::findById($object->getId());
                             if (!$file instanceof ProjectFile) {
                                 flash_error(lang('file dnx'));
                                 $err++;
                             }
                             // if
                             if (!$file->canDownload(logged_user())) {
                                 flash_error(lang('no access permissions'));
                                 $err++;
                             }
                             // if
                             $attachments[] = array("data" => $file->getFileContent(), "name" => $file->getFilename(), "type" => $file->getTypeString());
                         } else {
                             if ($split[0] == 'MailContents') {
                                 $email = MailContents::findById($object->getId());
                                 if (!$email instanceof MailContent) {
                                     flash_error(lang('email dnx'));
                                     $err++;
                                 }
                                 // if
                                 if (!$email->canView(logged_user())) {
                                     flash_error(lang('no access permissions'));
                                     $err++;
                                 }
                                 // if
                                 $attachments[] = array("data" => $email->getContent(), "name" => $email->getSubject() . ".eml", "type" => 'message/rfc822');
                             }
                         }
                     } else {
                         $linked_attachments[] = array("data" => $object->getViewUrl(), "name" => clean($object->getObjectName()), "type" => lang($object->getObjectTypeName()), "manager" => $object->getObjectManagerName(), "id" => $object->getId());
                     }
                 }
             }
             if ($err > 0) {
                 flash_error(lang('some objects could not be linked', $err));
                 ajx_current('empty');
                 return;
             }
         }
         $to = preg_split('/;|,/', $to);
         $to = $utils->parse_to($to);
         if ($body == '') {
             $body .= ' ';
         }
         try {
             if (count($linked_attachments)) {
                 $linked_users = array();
                 foreach ($to as $to_user) {
                     $linked_user = Users::getByEmail($to_user[1]);
                     if (!$linked_user instanceof User) {
                         try {
                             $linked_user = create_user_from_email($to_user[1], $to_user[0]);
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                     if ($linked_user instanceof User) {
                         $linked_users[] = $linked_user;
                     }
                 }
                 $linked_atts = $type == 'text/html' ? '<div style="font-family:arial;"><br><br><br><span style="font-size:12pt;font-weight:bold;color:#777">' . lang('linked attachments') . '</span><ul>' : "\n\n\n-----------------------------------------\n" . lang('linked attachments') . "\n\n";
                 foreach ($linked_attachments as $att) {
                     $linked_atts .= $type == 'text/html' ? '<li><a href="' . $att['data'] . '">' . $att['name'] . ' (' . $att['type'] . ')</a></li>' : $att['name'] . ' (' . $att['type'] . '): ' . $att['data'] . "\n";
                     foreach ($linked_users as $linked_user) {
                         try {
                             $linked_user->giveAccessToObject(get_object_by_manager_and_id($att['id'], $att['manager']));
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                 }
                 $linked_atts .= $type == 'text/html' ? '</ul></div>' : '';
             } else {
                 $linked_atts = '';
             }
             $body .= $linked_atts;
             if (count($attachments) > 0) {
                 $i = 0;
                 $str = "";
                 /*	foreach ($attachments as $att) {
                 					$str .= "--000000000000000000000000000$i\n";
                 					$str .= "Name: ".$att['name'] .";\n";
                 					$str .= "Type: ".$att['type'] .";\n";
                 					//$str .= "Encoding: ".$att['type'] .";\n";
                 					$str .= base64_encode($att['data']) ."\n";
                 					$str .= "--000000000000000000000000000$i--\n";
                 					$i++;
                 				}
                 			*/
                 $str = "#att_ver 2\n";
                 foreach ($attachments as $att) {
                     $rep_id = $utils->saveContent($att['data']);
                     $str .= $att['name'] . "," . $att['type'] . "," . $rep_id . "\n";
                 }
                 // save attachments, when mail is sent this file is deleted and full content is saved
                 $repository_id = $utils->saveContent($str);
                 if (!$isNew) {
                     if (FileRepository::isInRepository($mail->getContentFileId())) {
                         // delete old attachments
                         $content = FileRepository::getFileContent($mail->getContentFileId());
                         if (str_starts_with($content, "#att_ver")) {
                             $lines = explode("\n", $content);
                             foreach ($lines as $line) {
                                 if (!str_starts_with($line, "#") && trim($line) !== "") {
                                     $data = explode(",", $line);
                                     if (isset($data[2]) && FileRepository::isInRepository($data[2])) {
                                         FileRepository::deleteFile($data[2]);
                                     }
                                 }
                             }
                         }
                         FileRepository::deleteFile($mail->getContentFileId());
                     }
                 }
                 $mail->setContentFileId($repository_id);
             }
             $mail->setHasAttachments(is_array($attachments) && count($attachments) > 0 ? 1 : 0);
             $mail->setAccountEmail($account->getEmailAddress());
             $mail->setSentDate(DateTimeValueLib::now());
             $mail->setReceivedDate(DateTimeValueLib::now());
             DB::beginWork();
             $msg_id = MailUtilities::generateMessageId($account->getEmailAddress());
             $conversation_id = array_var($mail_data, 'conversation_id');
             $in_reply_to_id = array_var($mail_data, 'in_reply_to_id');
             if ($conversation_id) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent && $in_reply_to->getSubject() && strpos(strtolower($mail->getSubject()), strtolower($in_reply_to->getSubject())) === false) {
                     $conversation_id = null;
                     $in_reply_to_id = '';
                 }
             }
             if (!$conversation_id) {
                 $conversation_id = MailContents::getNextConversationId($account->getId());
             }
             $mail->setMessageId($msg_id);
             $mail->setConversationId($conversation_id);
             $mail->setInReplyToId($in_reply_to_id);
             $mail->setUid(gen_id());
             $mail->setState($isDraft ? 2 : 200);
             $mail->setIsPrivate(false);
             set_user_config_option('last_mail_format', array_var($mail_data, 'format', 'plain'), logged_user()->getId());
             $body = utf8_safe($body);
             if (array_var($mail_data, 'format') == 'html') {
                 $mail->setBodyHtml($body);
                 $mail->setBodyPlain(utf8_safe(html_to_text($body)));
             } else {
                 $mail->setBodyPlain($body);
                 $mail->setBodyHtml('');
             }
             $mail->setFrom($account->getEmailAddress());
             $mail->setFromName(logged_user()->getDisplayName());
             $mail->save();
             $mail->setIsRead(logged_user()->getId(), true);
             $mail->setTagsFromCSV(array_var($mail_data, 'tags'));
             // autoclassify sent email
             // if replying a classified email classify on same workspace
             $classified = false;
             if (array_var($mail_data, 'original_id')) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent) {
                     $workspaces = $in_reply_to->getWorkspaces();
                     foreach ($workspaces as $w) {
                         if ($mail->canAdd(logged_user(), $w)) {
                             $mail->addToWorkspace($w);
                             $classified = true;
                         }
                     }
                 }
             }
             if (!$classified && $account->getWorkspace() instanceof Project) {
                 $mail->addToWorkspace($account->getWorkspace());
             }
             if (!$classified && active_project() instanceof Project) {
                 $mail->addToWorkspace(active_project());
             }
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($mail);
             $object_controller->link_to_new_object($mail);
             if (array_var($mail_data, 'link_to_objects') != '') {
                 $lto = explode('|', array_var($mail_data, 'link_to_objects'));
                 foreach ($lto as $object_string) {
                     $split_object = explode('-', $object_string);
                     $object = get_object_by_manager_and_id($split_object[1], $split_object[0]);
                     if ($object instanceof ProjectDataObject) {
                         $mail->linkObject($object);
                     }
                 }
             }
             ApplicationLogs::createLog($mail, $mail->getWorkspaces(), ApplicationLogs::ACTION_ADD);
             if (user_config_option('create_contacts_from_email_recipients') && can_manage_contacts(logged_user())) {
                 // automatically create contacts
                 foreach ($to as $recipient) {
                     $recipient_name = trim($recipient[0]);
                     $recipient_address = trim($recipient[1]);
                     if (!$recipient_address) {
                         continue;
                     }
                     $contact = Contacts::getByEmail($recipient_address);
                     if (!$contact instanceof Contact) {
                         try {
                             $contact = new Contact();
                             $contact->setEmail($recipient_address);
                             if ($recipient_name && $recipient_name != $recipient_address) {
                                 $contact->setFirstName($recipient_name);
                             } else {
                                 $index = strpos($recipient_address, "@");
                                 $recipient_name = substr($recipient_address, 0, $index);
                                 $contact->setFirstName($recipient_name);
                             }
                             $contact->save();
                         } catch (Exception $e) {
                             // TODO: show error message?
                         }
                     }
                 }
             }
             DB::commit();
             if (!$autosave) {
                 if ($isDraft) {
                     flash_success(lang('success save mail'));
                     ajx_current("empty");
                 } else {
                     evt_add("must send mails", array("account" => $mail->getAccountId()));
                     //flash_success(lang('mail is being sent'));
                     ajx_current("back");
                 }
                 evt_add("email saved", array("id" => $mail->getId(), "instance" => array_var($_POST, 'instanceName')));
             } else {
                 evt_add("draft mail autosaved", array("id" => $mail->getId(), "hf_id" => $mail_data['hf_id']));
                 flash_success(lang('success autosave draft'));
                 ajx_current("empty");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Пример #27
0
	/**
	 * Add company
	 *
	 * @param void
	 * @return null
	 */
	function add_company() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		$notAllowedMember = '';				
		if(!Contact::canAdd(logged_user(),active_context(),$notAllowedMember)) {
			if (str_starts_with($notAllowedMember, '-- req dim --')) flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in)));
			else flash_error(lang('no context permissions to add',lang("contacts"), $notAllowedMember));
			ajx_current("empty");
			return;
		} // if
		
		$company = new Contact();
		$company->setIsCompany(1);
		$company_data = array_var($_POST, 'company');

		if(!is_array($company_data)) {
			$company_data = array(
				'timezone' => logged_user()->getTimezone(),
			); // array
		} // if
		tpl_assign('company', $company);
		tpl_assign('company_data', $company_data);
	
		if (is_array(array_var($_POST, 'company'))) {
                    
			$company->setFromAttributes($company_data);
			$company->setObjectName();

	

			try {
				Contacts::validate($company_data); 
				DB::beginWork();
				$company->save();
				if($company_data['address'] != "")
				$company->addAddress($company_data['address'], $company_data['city'], $company_data['state'], $company_data['country'], $company_data['zipcode'], 'work', true);
				if($company_data['phone_number'] != "") $company->addPhone($company_data['phone_number'], 'work', true);
				if($company_data['fax_number'] != "") $company->addPhone($company_data['fax_number'], 'fax', true);
				if($company_data['homepage'] != "") $company->addWebpage($company_data['homepage'], 'work');
				if($company_data['email'] != "") $company->addEmail($company_data['email'], 'work' , true);
				
				$object_controller = new ObjectController();
				$object_controller->add_subscribers($company);

				$member_ids = json_decode(array_var($_POST, 'members'));
				if (!is_null($member_ids)) {
					$object_controller->add_to_members($company, $member_ids);
				}
				$object_controller->link_to_new_object($company);
				$object_controller->add_custom_properties($company);
				
				ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD);

				DB::commit();

				flash_success(lang('success add client', $company->getObjectName()));
				evt_add("company added", array("id" => $company->getObjectId(), "name" => $company->getObjectName()));
				ajx_current("back");
			} catch(Exception $e) {
				DB::rollback();
				ajx_current("empty");
				flash_error($e->getMessage());
			} // try
		} // if
	} // add_company
 function checkin_file()
 {
     $this->setTemplate('add_file');
     $file = ProjectFiles::findById(get_id());
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$file->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $file_data = array_var($_POST, 'file');
     if (!is_array($file_data)) {
         $tag_names = $file->getTagNames();
         $file_data = array('description' => $file->getDescription(), 'is_private' => $file->getIsPrivate(), 'is_important' => $file->getIsImportant(), 'comments_enabled' => $file->getCommentsEnabled(), 'anonymous_comments_enabled' => $file->getAnonymousCommentsEnabled(), 'tags' => is_array($tag_names) && count($tag_names) ? implode(', ', $tag_names) : '', 'workspaces' => $file->getWorkspacesNamesCSV(logged_user()->getWorkspacesQuery()));
         // array
     }
     // if
     tpl_assign('file', $file);
     tpl_assign('file_data', $file_data);
     tpl_assign('checkin', true);
     if (is_array(array_var($_POST, 'file'))) {
         try {
             $old_is_private = $file->isPrivate();
             $old_is_important = $file->getIsImportant();
             $old_comments_enabled = $file->getCommentsEnabled();
             $old_anonymous_comments_enabled = $file->getAnonymousCommentsEnabled();
             DB::beginWork();
             $handle_file = true;
             // change file?
             $post_revision = $handle_file && array_var($file_data, 'version_file_change') == 'checked';
             // post revision?
             $revision_comment = $post_revision ? trim(array_var($file_data, 'revision_comment')) : '';
             // user comment?
             $file->setFromAttributes($file_data);
             $file->setFilename(array_var($file_data, 'name'));
             $file->checkIn();
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $file->setIsPrivate($old_is_private);
                 $file->setIsImportant($old_is_important);
                 $file->setCommentsEnabled($old_comments_enabled);
                 $file->setAnonymousCommentsEnabled($old_anonymous_comments_enabled);
             }
             // if
             $file->save();
             $file->setTagsFromCSV(array_var($file_data, 'tags'));
             if ($handle_file) {
                 // handle uploaded file
                 $upload_id = array_var($file_data, 'upload_id');
                 $uploaded_file = array_var($_SESSION, $upload_id, array());
                 $file->handleUploadedFile($uploaded_file, $post_revision, $revision_comment);
                 // handle uploaded file
                 @unlink($uploaded_file['tmp_name']);
             }
             // if
             $ws = $file->getWorkspaces();
             $object_controller = new ObjectController();
             $object_controller->link_to_new_object($file);
             $object_controller->add_subscribers($file);
             $object_controller->add_custom_properties($file);
             ApplicationLogs::createLog($file, $ws, ApplicationLogs::ACTION_EDIT);
             ApplicationLogs::createLog($file, $file->getWorkspaces(), ApplicationLogs::ACTION_CHECKIN);
             DB::commit();
             flash_success(lang('success add file', $file->getFilename()));
             ajx_current("back");
         } catch (Exception $e) {
             //@unlink($file->getFilePath());
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Пример #29
0
 /**
  * Return tag names as array ordered by occurrence
  * $order_by sort order, possible values are 'name' and 'count'
  *
  * @access public
  * @return array
  */
 function getTagNames($order_by = 'count')
 {
     $oc = new ObjectController();
     $dqs = $oc->getDashboardObjectQueries();
     $conditions = "";
     foreach ($dqs as $type => $q) {
         if (substr($type, -8) == 'Comments') {
             continue;
         }
         $q = substr($q, strpos($q, "FROM"));
         $q = "`rel_object_id` IN (SELECT `id` {$q}) AND `rel_object_manager` = '{$type}'";
         if ($conditions) {
             $conditions .= " \n\nOR\n\n ";
         }
         $conditions .= $q;
     }
     $query = '';
     switch ($order_by) {
         case 'name':
             $query = 'SELECT DISTINCT `tag` as `name`  FROM ' . self::instance()->getTableName(true) . ' WHERE' . $conditions . ' GROUP BY `tag` ORDER BY  `tag` ';
             break;
         case 'count':
         default:
             $query = 'SELECT DISTINCT `tag` as `name`, count(`tag`) `count` FROM ' . self::instance()->getTableName(true) . ' WHERE' . $conditions . ' GROUP BY `tag` ORDER BY `count` DESC , `tag`';
     }
     $rows = DB::executeAll($query);
     if (!is_array($rows)) {
         return array();
     }
     return $rows;
 }
Пример #30
0
	private function upload_file($file, $filename, $path, $members) {
		try {
			if ($file == null) {
				$file = new ProjectFile();
				$file->setFilename($filename);
				$file->setIsVisible(true);
				$file->setCreatedOn(new DateTimeValue(time()));
			}

			$file_dt['name'] = $file->getFilename();
			$file_dt['size'] = filesize($path);
			$file_dt['tmp_name'] = $path;
			$extension = trim(get_file_extension($filename));
			$file_dt['type'] = Mime_Types::instance()->get_type($extension);

			if(!trim($file_dt['type'])) $file_dt['type'] = 'text/html';

			DB::beginWork();
			$file->save();
			$ctrl = new ObjectController() ;
			if (is_array($members)) {
				$ctrl->add_to_members($file, array_flat($members));
			}
			
			$revision = $file->handleUploadedFile($file_dt, true, '');

			ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD);
			DB::commit();
			return true;
		} catch (Exception $e) {
			DB::rollback();
			flash_error($e->getMessage());
			ajx_current("empty");
		}
		return false;
	} // upload_extracted_file