PageRenderTime 83ms CodeModel.GetById 3ms app.highlight 69ms RepoModel.GetById 2ms app.codeStats 0ms

/application/controllers/ProjectController.class.php

https://github.com/fb83/Project-Pier
PHP | 1506 lines | 1087 code | 214 blank | 205 comment | 190 complexity | 0876b93b35635e7b00a41654915e17cc MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2
   3  /**
   4  * Project controller
   5  *
   6  * @version 1.0
   7  * @http://www.projectpier.org/
   8  */
   9  class ProjectController extends ApplicationController {
  10    
  11    /**
  12    * Prepare this controller
  13    *
  14    * @param void
  15    * @return ProjectController
  16    */
  17    function __construct() {
  18      parent::__construct();
  19      prepare_company_website_controller($this, 'project_website');
  20    } // __construct
  21    
  22    /**
  23    * Call overview action
  24    *
  25    * @param void
  26    * @return null
  27    */
  28    function index() {
  29      $this->forward('overview');
  30    } // index
  31    
  32    /**
  33    * Show project overview
  34    *
  35    * @param void
  36    * @return null
  37    */
  38    function overview() {
  39      if (active_project() == null || !logged_user()->isProjectUser(active_project())) {
  40        flash_error(lang('no access permissions'));
  41        $this->redirectTo('dashboard', 'index');
  42      } // if
  43      
  44      $this->addHelper('textile');
  45      
  46      $project = active_project();
  47      
  48      $page_attachments = PageAttachments::getAttachmentsByPageNameAndProject('project_overview', active_project());
  49      
  50      $this->setLayout('project_website');
  51      tpl_assign('page_attachments', $page_attachments);
  52      tpl_assign('project_log_entries', $project->getProjectLog(
  53        config_option('project_logs_per_page', 20)
  54      ));
  55      tpl_assign('project', $project);
  56      tpl_assign('subprojects', $project->getSubprojects());
  57      tpl_assign('late_milestones', $project->getLateMilestones());
  58      tpl_assign('today_milestones', $project->getTodayMilestones());
  59      tpl_assign('upcoming_milestones', $project->getUpcomingMilestones());
  60      
  61      // Sidebar
  62      tpl_assign('visible_forms', $project->getVisibleForms(true));
  63      tpl_assign('project_companies', $project->getVisibleCompanies(logged_user()));
  64      tpl_assign('project_users', $project->getVisibleUsers(logged_user()));
  65      tpl_assign('important_messages', active_project()->getImportantMessages());
  66      tpl_assign('important_files', active_project()->getImportantFiles());
  67      
  68      $this->setSidebar(get_template_path('overview_sidebar', 'project'));
  69    } // overview
  70    
  71    /**
  72    * Execute search
  73    *
  74    * @param void
  75    * @return null
  76    */
  77    function search() {
  78      if (!logged_user()->isProjectUser(active_project())) {
  79        flash_error(lang('no access permissions'));
  80        $this->redirectTo('dashboard');
  81      } // if
  82
  83      $search_for = array_var($_GET, 'search_for');
  84      $page = (integer) array_var($_GET, 'page', 1);
  85      if ($page < 1) {
  86        $page = 1;
  87      }
  88      
  89      if (trim($search_for) == '') {
  90        $search_results = null;
  91        $pagination = null;
  92      } else {
  93        list($search_results, $pagination) = SearchableObjects::searchPaginated($search_for, active_project(), logged_user()->isMemberOfOwnerCompany(), 10, $page);
  94      } // if
  95      
  96      tpl_assign('search_string', $search_for);
  97      tpl_assign('current_page', $page);
  98      tpl_assign('search_results', $search_results);
  99      tpl_assign('pagination', $pagination);
 100
 101      $tag_names = plugin_active('tags') ? active_project()->getTagNames() : '';
 102      tpl_assign('tag_names', $tag_names);
 103      $this->setSidebar(get_template_path('search_sidebar', 'project'));
 104    } // search
 105    
 106    /**
 107    * Show tags page
 108    *
 109    * @param void
 110    * @return null
 111    */
 112    function tags() {
 113      if (!logged_user()->isProjectUser(active_project())) {
 114        flash_error(lang('no access permissions'));
 115        $this->redirectTo('dashboard', 'index');
 116      } // if
 117      
 118      tpl_assign('tag_names', active_project()->getTagNames());
 119    } // tags
 120    
 121    /**
 122    * List all companies and users involved in this project
 123    *
 124    * @param void
 125    * @return null
 126    */
 127    function people() {
 128      if (!logged_user()->isProjectUser(active_project())) {
 129        flash_error(lang('no access permissions'));
 130        $this->redirectTo('dashboard', 'index');
 131      } // if
 132      
 133      $this->addHelper('textile');
 134      $page_attachments = PageAttachments::getAttachmentsByTypeAndProject(array('Contacts', 'Companies'), active_project());
 135      tpl_assign('page_attachments', $page_attachments);
 136      tpl_assign('project', active_project());
 137
 138    } // people
 139    
 140    /**
 141    * Show permission update form
 142    *
 143    * @param void
 144    * @return null
 145    */
 146    function permissions() {
 147      $project = active_project();
 148      if (!$project->canChangePermissions(logged_user())) {
 149        flash_error(lang('no access permissions'));
 150        $this->redirectToUrl($project->getOverviewUrl());
 151      } // if
 152      
 153      tpl_assign('project_users', $project->getUsers(false));
 154      tpl_assign('project_companies', $project->getCompanies());
 155      tpl_assign('user_projects', logged_user()->getProjects());
 156      
 157      $permissions = PermissionManager::getPermissionsText();
 158      tpl_assign('permissions', $permissions);
 159      
 160      $companies = array(owner_company());
 161      $clients = owner_company()->getClientCompanies();
 162      if (is_array($clients)) {
 163        $companies = array_merge($companies, $clients);
 164      } // if
 165      tpl_assign('companies', $companies);
 166      
 167      if (array_var($_POST, 'process') == 'process') {
 168        try {
 169          DB::beginWork();
 170          
 171          $project->clearCompanies();
 172          $project->clearUsers();
 173          
 174          $companies = array(owner_company());
 175          $client_companies = owner_company()->getClientCompanies();
 176          if (is_array($client_companies)) {
 177            $companies = array_merge($companies, $client_companies);
 178          } // if
 179          
 180          foreach ($companies as $company) {
 181            trace(__FILE__,"permissions(): processing company {$company->getId()}");
 182            // Company is selected!
 183            if (array_var($_POST, 'project_company_' . $company->getId()) == 'checked') {
 184              
 185              $is_owner_company = $company->isOwner();
 186  
 187              // Owner company is automatically included so it does not need to be in project_companies table
 188              if (!$is_owner_company) {
 189                $project_company = new ProjectCompany();
 190                $project_company->setProjectId(active_project()->getId());
 191                $project_company->setCompanyId($company->getId());
 192                $project_company->save();
 193              } // if
 194              
 195              $users = $company->getUsers();
 196              if (is_array($users)) {
 197                $counter = 0;
 198                foreach ($users as $user) {
 199                  trace(__FILE__,"permissions(): processing user {$user->getId()} in company {$company->getId()}");
 200                  $user_id = $user->getId();
 201                  $counter++;
 202                  if (array_var($_POST, "project_user_$user_id") == 'checked') {
 203                    
 204                    $project_user = new ProjectUser();
 205                    $project_user->setProjectId($project->getId());
 206                    $project_user->setUserId($user_id);
 207                    $project_user->save();
 208                    
 209                    foreach ($permissions as $permission_name => $permission_text) {
 210                      
 211                      // Owner company members have all permissions
 212                      $permission_value = $is_owner_company ? true : array_var($_POST, 'project_user_' . $user_id . '_' . $permission_name) == 'checked';
 213
 214                      //$user = Users::findById($project_user->getUserId());
 215                      trace(__FILE__,"permissions(): processing permission $permission_name=$permission_value for user {$user->getId()} in company {$company->getId()}");
 216                      $user->setProjectPermission($project,$permission_name,$permission_value);
 217                    } // if
 218                   
 219                  } // if
 220                  
 221                } // foreach
 222              } // if
 223            } // if
 224          } // foreach
 225          
 226          DB::commit();
 227          
 228          flash_success(lang('success update project permissions'));
 229          $this->redirectTo('project', 'overview');
 230        } catch(Exception $e) {
 231          DB::rollback();
 232          flash_error(lang('error update project permissions', $e->__toString() ));
 233          $this->redirectTo('project', 'permissions');
 234        } // try
 235      } // if
 236    } // permissions
 237  
 238    /**
 239    * Add project
 240    *
 241    * @param void
 242    * @return null
 243    */
 244    function add() {
 245      $this->setTemplate('add_project');
 246      $this->setLayout('administration');
 247      
 248      if (!logged_user()->canManageProjects()) {
 249        flash_error(lang('no access permissions'));
 250        $this->redirectToReferer(get_url('dashboard'));
 251      } // if
 252      
 253      $project = new Project();
 254      
 255      $project_data = array_var($_POST, 'project');
 256      $page_name = 'project_overview';
 257      $page_attachments = PageAttachments::getAttachmentsByPageNameAndProject($page_name, $project);
 258      $redirect_to = urldecode(array_var($_GET, 'redirect_to'));
 259      
 260      tpl_assign('project', $project);
 261      tpl_assign('project_data', $project_data);
 262      tpl_assign('page_attachments', $page_attachments);
 263      tpl_assign('redirect_to', $redirect_to);
 264      
 265      // Submitted...
 266      if (is_array($project_data)) {
 267        $project->setFromAttributes($project_data);
 268        
 269        $default_folders = array();
 270        if (plugin_active('files')) {
 271          $default_folders_config = str_replace(array("\r\n", "\r"), array("\n", "\n"), config_option('default_project_folders', ''));
 272          if (trim($default_folders_config) == '') {
 273            $default_folders = array();
 274          } else {
 275            $default_folders = explode("\n", $default_folders_config);
 276          } // if
 277        } // if
 278
 279        $default_ticket_categories = array();
 280        if (plugin_active('tickets')) {
 281          $default_ticket_categories_config = str_replace(array("\r\n", "\r"), array("\n", "\n"), config_option('tickets_default_categories', ''));
 282          if (trim($default_ticket_categories_config) == '') {
 283            $default_ticket_categories = array();
 284          } else {
 285            $default_ticket_categories = explode("\n", $default_ticket_categories_config);
 286          } // if
 287        } // if
 288        
 289        try {
 290          DB::beginWork();
 291          $project->save();
 292          
 293          $permissions = array_keys(PermissionManager::getPermissionsText());
 294          $auto_assign_users = owner_company()->getAutoAssignUsers();
 295          
 296          // We are getting the list of auto assign users. If current user is not in the list
 297          // add it. He's creating the project after all...
 298          if (is_array($auto_assign_users)) {
 299            $auto_assign_logged_user = false;
 300            foreach ($auto_assign_users as $user) {
 301              if ($user->getId() == logged_user()->getId()) {
 302                $auto_assign_logged_user = true;
 303              }
 304            } // if
 305            if (!$auto_assign_logged_user) {
 306              $auto_assign_users[] = logged_user();
 307            }
 308          } else {
 309            $auto_assign_users[] = logged_user();
 310          } // if
 311          
 312          foreach ($auto_assign_users as $auto_assign_user) {
 313            $project_user = new ProjectUser();
 314            $project_user->setProjectId($project->getId());
 315            $project_user->setUserId($auto_assign_user->getId());
 316            $project_user->save();
 317            if (is_array($permissions)) {
 318              foreach ($permissions as $permission) {
 319                $auto_assign_user->setProjectPermission($project,$permission,true);
 320              }
 321            } // if
 322          } // foreach
 323          
 324          if (count($default_folders)) {
 325            $added_folders = array();
 326            foreach ($default_folders as $default_folder) {
 327              $folder_name = trim($default_folder);
 328              if ($folder_name == '') {
 329                continue;
 330              } // if
 331              
 332              if (in_array($folder_name, $added_folders)) {
 333                continue;
 334              } // if
 335              
 336              $folder = new ProjectFolder();
 337              $folder->setProjectId($project->getId());
 338              $folder->setName($folder_name);
 339              $folder->save();
 340              
 341              $added_folders[] = $folder_name;
 342            } // foreach
 343          } // if
 344          
 345          if (count($default_ticket_categories)) {
 346            $added_categories = array();
 347            foreach ($default_ticket_categories as $default_ticket_category) {
 348              $category_name = trim($default_ticket_category);
 349              if ($category_name == '') {
 350                continue;
 351              } // if
 352              
 353              if (in_array($category_name, $added_categories)) {
 354                continue;
 355              } // if
 356              
 357              $folder = new ProjectCategory();
 358              $folder->setProjectId($project->getId());
 359              $folder->setName($category_name);
 360              $folder->save();
 361              
 362              $added_categories[] = $category_name;
 363            } // foreach
 364          } // if
 365
 366          $efqm_project = (isset($project_data['efqm_project'])) ? ($project_data['efqm_project']=='1') : false;
 367          if ($efqm_project) {
 368            // insert 9 milestones with task lists
 369            $efqm_template = array(
 370              'efqm leadership' => array('a', 'b', 'c', 'd', 'e'),
 371              'efqm strategy' => array('a', 'b', 'c', 'd'),
 372              'efqm people' => array('a', 'b', 'c', 'd', 'e'),
 373              'efqm partnership and resources' => array('a', 'b', 'c', 'd', 'e'),
 374              'efqm processes products services' => array('a', 'b', 'c', 'd', 'e'),
 375              'efqm customer results' => array('a', 'b'),
 376              'efqm people results' => array('a', 'b'),
 377              'efqm society results' => array('a', 'b'),
 378              'efqm key results' => array('a', 'b'),
 379            );
 380            foreach($efqm_template as $criteria => $subcriteria) { 
 381              $milestone = new ProjectMilestone();
 382              $milestone->setProjectId($project->getId());
 383              $milestone->setName(lang($criteria));
 384              $milestone->setGoal(config_option('initial goal', 80));
 385              $milestone->setDueDate(DateTimeValueLib::now());
 386              $offset_in_days = config_option('due date offset', 90);
 387              $milestone->getDueDate()->advance(60*60*24*$offset_in_days);
 388              $milestone->save();
 389              foreach($subcriteria as $subname) { 
 390                $task_list = new ProjectTaskList();
 391                $task_list->setMilestoneId($milestone->getId());
 392                $task_list->setProjectId($project->getId());
 393                $task_list->setName(lang($criteria) . ' ' . $subname);
 394                $task_list->setDueDate($milestone->getDueDate());
 395                $task_list->setScore(config_option('initial score', 50));
 396                $task_list->save();
 397              }
 398            }
 399          }
 400
 401          ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_ADD, false, true);
 402          DB::commit();
 403          
 404          flash_success(lang('success add project', $project->getName()));
 405          $this->redirectToUrl($project->getPermissionsUrl());
 406          
 407        } catch(Exception $e) {
 408          tpl_assign('error', $e);
 409          DB::rollback();
 410        } // try
 411        
 412      } // if
 413      
 414    } // add
 415    
 416    /**
 417    * Copy project
 418    *
 419    * @param void
 420    * @return null
 421    */
 422    function copy() {
 423      trace(__FILE__,"copy():begin");   
 424      if (!Project::canAdd(logged_user())) {
 425        flash_error(lang('no access permissions'));
 426        $this->redirectToReferer(get_url('dashboard'));
 427      } // if
 428      
 429      $this->setTemplate('copy_project');
 430      $this->setLayout('administration');
 431      
 432      $project_data = array_var($_POST, 'project');
 433      tpl_assign('project_data', $project_data);
 434      
 435      // Submitted...
 436      if (is_array($project_data)) {
 437        $source = Projects::findById($project_data['source']);
 438        if (!($source instanceof Project)) {
 439          flash_error(lang('project dnx'));
 440          $this->redirectTo('administration', 'projects');
 441        } // if
 442        try {
 443          $shift_dates = (isset($project_data['shift_dates'])) ? ($project_data['shift_dates']=='checked') : false;
 444          $copy_details = (isset($project_data['copy_details'])) ? ($project_data['copy_details']=='checked') : false;
 445          $copy_tasks = (isset($project_data['copy_tasks'])) ? ($project_data['copy_tasks']=='checked') : false;
 446          $copy_milestones = (isset($project_data['copy_milestones'])) ? ($project_data['copy_milestones']=='checked') : false;
 447          $copy_messages = (isset($project_data['copy_messages'])) ? ($project_data['copy_messages']=='checked') : false;
 448          $copy_links = (isset($project_data['copy_links'])) ? ($project_data['copy_links']=='checked') : false;
 449          $copy_files = (isset($project_data['copy_files'])) ? ($project_data['copy_files']=='checked') : false;
 450          $copy_users = (isset($project_data['copy_users'])) ? ($project_data['copy_users']=='checked') : false;
 451          $copy_pages = (isset($project_data['copy_pages'])) ? ($project_data['copy_pages']=='checked') : false;
 452
 453          DB::beginWork();
 454
 455          $project = new Project();
 456          $new_name = lang( 'projects copy new name', $source->getName() );
 457          $new_name .= date(' z H:i:s');
 458          $project->setName($new_name);
 459          if ($copy_details) {
 460             $project->setDescription( $source->getDescription() );
 461             $project->setPriority( $source->getPriority() );
 462             $project->setShowDescriptionInOverview( $source->getShowDescriptionInOverview() );
 463          }
 464          $project->save();
 465          $project_id = $project->getId();
 466
 467          $add_seconds = 0;
 468          if (isset($project_data['add_days'])) { 
 469             $add_days = 0 + trim( $project_data['add_days'] );
 470             $add_seconds = $add_days * 24 * 60 * 60;
 471          }
 472
 473          $source_created_on = $source->getCreatedOn();
 474          //var_dump($source_created_on);
 475          $milestone_map = array( 0 => 0 );
 476
 477          // project milestones
 478          if ($copy_milestones) {
 479            $source_milestones = $source->getAllMilestones();
 480            if (is_array($source_milestones)) {
 481              foreach ($source_milestones as $source_milestone) {
 482                $milestone = new ProjectMilestone();
 483                //$milestone->copy($source_milestone);
 484                $milestone->setName($source_milestone->getName());
 485                $milestone->setDescription($source_milestone->getDescription());
 486                if ($shift_dates) {
 487                  trace(__FILE__,"copy():shift dates");   
 488                  $milestone->setDueDate(DateTimeValueLib::now());
 489                  $seconds = $source_milestone->getDueDate()->difference($source_created_on);
 490                  $milestone->getDueDate()->advance($seconds);
 491                } else {
 492                  $milestone->setDueDate($source_milestone->getDueDate());
 493                }
 494                $milestone->getDueDate()->advance($add_seconds);
 495                $milestone->setIsPrivate($source_milestone->getIsPrivate());
 496                $milestone->setAssignedToUserId($source_milestone->getAssignedToUserId());
 497                $milestone->setAssignedToCompanyId($source_milestone->getAssignedToCompanyId());
 498                $milestone->setProjectId($project_id);
 499                $milestone->save();
 500                $milestone_map[$source_milestone->getId()]=$milestone->getId();
 501              } // foreach
 502            } // if
 503          } // if
 504
 505          // project tasks
 506          if ($copy_tasks) {
 507            $source_task_lists = $source->getAllTaskLists();
 508            if (is_array($source_task_lists)) {
 509              foreach ($source_task_lists as $source_task_list) {
 510                $task_list = new ProjectTaskList();
 511                //$task_list->copy($source_milestone);
 512                $task_list->setName($source_task_list->getName());
 513                $task_list->setPriority($source_task_list->getPriority());
 514                $task_list->setDescription($source_task_list->getDescription());
 515                if ($copy_milestones) {
 516                  $task_list->setMilestoneId($milestone_map[$source_task_list->getMilestoneId()]);
 517                }
 518                $task_list->setDueDate($source_task_list->getDueDate());
 519                if ($task_list->getDueDate() instanceof DateTimeValue) {
 520                  if ($shift_dates) {
 521                    trace(__FILE__,"copy():task list shift dates");   
 522                    $task_list->setDueDate(DateTimeValueLib::now());
 523                    $seconds = $source_task_list->getDueDate()->difference($source_created_on);
 524                    $task_list->getDueDate()->advance($seconds);
 525                  }
 526                  $task_list->getDueDate()->advance($add_seconds);
 527                }
 528                $task_list->setIsPrivate($source_task_list->getIsPrivate());
 529                $task_list->setOrder($source_task_list->getOrder());
 530                $task_list->setProjectId($project_id);
 531                $task_list->save();
 532                $source_tasks = $source_task_list->getTasks();
 533                if (is_array($source_tasks)) {
 534                  foreach($source_tasks as $source_task) {
 535                    $task = new ProjectTask();
 536                    $task->setOrder($source_task->getOrder());
 537                    $task->setDueDate($source_task->getDueDate());
 538                    if ($task->getDueDate() instanceof DateTimeValue) {
 539                      if ($shift_dates) {
 540                        trace(__FILE__,"copy():task shift dates");   
 541                        $task->setDueDate(DateTimeValueLib::now());
 542                        $seconds = $source_task->getDueDate()->difference($source_created_on);
 543                        $task->getDueDate()->advance($seconds);
 544                      }
 545                      $task->getDueDate()->advance($add_seconds);
 546                    }
 547                    $task->setText($source_task->getText());
 548                    $task->getAssignedToUserId($source_task->getAssignedToUserId());
 549                    $task->getAssignedToCompanyId($source_task->getAssignedToCompanyId());
 550                    $task_list->attachTask($task);
 551                  }
 552                }
 553              } // foreach
 554            } // if
 555          } // if
 556
 557          // project messages
 558          if ($copy_messages) {
 559            $source_messages= $source->getAllMessages();
 560            if (is_array($source_messages)) {
 561              foreach ($source_messages as $source_message) {
 562                $message = new ProjectMessage();
 563                //$message->copy($source_message);
 564                $message->setTitle($source_message->getTitle());
 565                $message->setText($source_message->getText());
 566                $message->setAdditionalText($source_message->getAdditionalText());
 567                if ($copy_milestones) {
 568                  $message->setMilestoneId($milestone_map[$source_message->getMilestoneId()]);
 569                }
 570                $message->setIsImportant($source_message->getIsImportant());
 571                $message->setIsPrivate($source_message->getIsPrivate());
 572                $message->setCommentsEnabled($source_message->getCommentsEnabled());
 573                $message->setAnonymousCommentsEnabled($source_message->getAnonymousCommentsEnabled());
 574                $message->setProjectId($project_id);
 575                $message->save();
 576              } // foreach
 577            } // if
 578          } // if
 579
 580          // project links
 581          if ($copy_links) {
 582            $source_links = ProjectLinks::getAllProjectLinks($source);
 583            if (is_array($source_links)) {
 584              foreach ($source_links as $source_link) {
 585                $link = new ProjectLink();
 586                //$folder->copy($source_link);
 587                $link->setTitle($source_link->getTitle());
 588                $link->setUrl($source_link->getUrl());
 589                $link->setProjectId($project_id);
 590                $link->save();
 591              } // foreach
 592            } // if
 593          } // if
 594
 595          // project folders & files  
 596          if ($copy_files) {
 597            $folder_map = array( 0 => 0 );
 598            $source_folders = $source->getFolders();
 599            if (is_array($source_folders)) {
 600              foreach ($source_folders as $source_folder) {
 601                $folder = new ProjectFolder();
 602                //$folder->copy($source_folder);
 603                $folder->setName($source_folder->getName());
 604                $folder->setProjectId($project_id);
 605                $folder->save();
 606                $folder_map[$source_folder->getId()]=$folder->getId();
 607              } // foreach
 608            } // if
 609            $source_files = ProjectFiles::getAllFilesByProject($source);
 610            if (is_array($source_files)) {
 611              foreach ($source_files as $source_file) {
 612                $file = new ProjectFile();
 613                $file->setProjectId($project_id);
 614                $file->setFolderId($folder_map[$source_file->getFolderId()]);
 615                $file->setFileName($source_file->getFileName());
 616                $file->setDescription($source_file->getDescription());
 617                $file->setIsPrivate($source_file->getIsPrivate());
 618                $file->setIsImportant($source_file->getIsImportant());
 619                $file->setIsLocked($source_file->getIsLocked());
 620                $file->setIsVisible($source_file->getIsVisible());
 621                $file->setExpirationTime($source_file->getExpirationTime());
 622                $file->setCommentsEnabled($source_file->getCommentsEnabled());
 623                $file->setAnonymousCommentsEnabled($source_file->getAnonymousCommentsEnabled());
 624                $file->save();
 625                $source_revision = $source_file->getLastRevision();
 626                if ($source_revision instanceof ProjectFileRevision) {
 627                  $revision = new ProjectFileRevision();
 628                  $revision->setFileId($file->getId());
 629                  $revision->setRevisionNumber($source_revision->getRevisionNumber());
 630                  $revision->setRepositoryId($source_revision->getRepositoryId());
 631                  $revision->setFilesize($source_revision->getFilesize());
 632                  $revision->setFilename($source_revision->getFileName());
 633                  $revision->setTypeString($source_revision->getTypeString());
 634                  $revision->setThumbFilename($source_revision->getThumbFilename());
 635                  $revision->setFileTypeId($source_revision->getFileTypeId());
 636                  $revision->setComment($source_revision->getComment());
 637                  $revision->save();
 638                }
 639              } // foreach
 640            } // if
 641          } // if
 642          if ($copy_pages) {
 643            $source_pages = Wiki::getAllProjectPages($source);
 644            if (is_array($source_pages)) {
 645              foreach ($source_pages as $source_page) {
 646                $page = new WikiPage();
 647		$page->setProjectId($project_id);
 648		$page->setProjectIndex($source_page->getProjectIndex());
 649		$page->setProjectSidebar($source_page->getProjectSidebar());
 650                if (plugin_active('tags')) {
 651                  //$page->setTags($source_page->getTagNames());
 652		}
 653	
 654		//Make a new revision of this page
 655		$revision = $page->makeRevision();
 656
 657                $source_revision = $source_page->getLatestRevision();
 658			
 659		//Set attributes
 660                $revision->setName($source_revision->getName());
 661                $revision->setContent($source_revision->getContent());
 662                $revision->setLogMessage($source_revision->getLogMessage());
 663		//Save the page
 664                $page->save();
 665              } // foreach
 666            } // if
 667          } // if
 668          
 669          if ($copy_users) {
 670
 671            $source_companies = ProjectCompanies ::instance()->getCompaniesByProject($source);
 672            if (is_array($source_companies)) {
 673              foreach ($source_companies as $source_company) {
 674                $project_company = new ProjectCompany();
 675                $project_company->setCompanyId($source_company->getId());
 676                $project_company->setProjectId($project_id);
 677                $project_company->save();
 678              } // foreach
 679            }
 680
 681            $source_users = ProjectUsers::instance()->getUsersByProject($source);
 682            if (is_array($source_users)) {
 683              foreach ($source_users as $source_user) {
 684                $project_user = new ProjectUser();
 685                $project_user->setUserId($source_user->getId());
 686                $project_user->setProjectId($project_id);
 687                $project_user->save();
 688              } // foreach
 689            }
 690
 691          }
 692/*
 693          $permissions = array_keys(PermissionManager::getPermissionsText());
 694          $auto_assign_users = owner_company()->getAutoAssignUsers();
 695          
 696          // We are getting the list of auto assign users. If current user is not in the list
 697          // add it. He's creating the project after all...
 698          if (is_array($auto_assign_users)) {
 699            $auto_assign_logged_user = false;
 700            foreach ($auto_assign_users as $user) {
 701              if ($user->getId() == logged_user()->getId()) {
 702                $auto_assign_logged_user = true;
 703              }
 704            } // if
 705            if (!$auto_assign_logged_user) {
 706              $auto_assign_users[] = logged_user();
 707            }
 708          } else {
 709            $auto_assign_users[] = logged_user();
 710          } // if
 711          
 712          foreach ($auto_assign_users as $user) {
 713            $project_user = new ProjectUser();
 714            $project_user->setProjectId($project->getId());
 715            $project_user->setUserId($user->getId());
 716            if (is_array($permissions)) {
 717              foreach ($permissions as $permission) {
 718                $user = Users::findById($project_user->getUserId());
 719                $user->setProjectPermission($project,$permission,true);
 720              }
 721            } // if
 722            $project_user->save();
 723          } // foreach
 724*/
 725          ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_ADD, false, true);
 726          DB::commit();
 727          
 728          flash_success(lang('success copy project', $source->getName(), $project->getName()));
 729          $this->redirectToUrl($project->getPermissionsUrl());
 730          
 731        } catch(Exception $e) {
 732          echo $e->getMessage();
 733          tpl_assign('error', $e);
 734          DB::rollback();
 735        } // try
 736      
 737      } // if (submitted)
 738      
 739    } // copy 
 740
 741    /**
 742    * Download project task lists
 743    *
 744    * @param void
 745    * @return null
 746    */
 747    function download_task_lists() {
 748      if (!logged_user()->isProjectUser(active_project())) {
 749        flash_error(lang('no access permissions'));
 750        $this->redirectTo('dashboard', 'index');
 751      } // if
 752      $project = active_project();
 753      $task_lists = $project->getTaskLists();
 754      $project_name = $project->getName();
 755      if (is_array($task_lists)) {
 756        $name = $project_name.'_tasks.txt';
 757        $content = '';
 758        $header = true;
 759        $count = 0;
 760        foreach ($task_lists as $task_list) {
 761          $content .= $task_list->getDownloadText($count, "\t", $header);
 762          $header = false;
 763        }
 764        //flash_success(lang('%s items downloaded', $count));
 765        download_contents($content, 'text/csv', $name, strlen($content));
 766        die();
 767      } else {
 768        flash_error(lang('nothing to download', $project_name));
 769      }
 770      $this->redirectTo('project', 'index');
 771    }
 772
 773    /**
 774    * Edit project
 775    *
 776    * @param void
 777    * @return null
 778    */
 779    function edit() {
 780      $project = Projects::findById(get_id());
 781      if (!($project instanceof Project)) {
 782        flash_error(lang('project dnx'));
 783        $this->redirectTo('dashboard', 'index');
 784      } // if
 785      
 786      if (!$project->canEdit(logged_user())) {
 787        flash_error(lang('no access permissions'));
 788        $this->redirectToReferer(get_url('dashboard', 'index'));
 789      } // if
 790
 791      if (plugin_active('files')) {
 792        $this->addHelper('files', 'files');
 793      }
 794      if (plugin_active('tickets')) {
 795        $this->addHelper('tickets', 'tickets');
 796      }
 797      // TODO find a more elegant solution for this parameter
 798      $page_name = 'project_overview';
 799      $this->setTemplate('add_project');
 800      $this->setLayout('project_website');
 801      $this->setSidebar(get_template_path('textile_help_sidebar'));
 802      
 803      $project_data = array_var($_POST, 'project');
 804      if (!is_array($project_data)) {
 805        $project_data = array(
 806          'name' => $project->getName(),
 807          'parent_id' => $project->getParentId(),
 808          'priority' => $project->getPriority(),
 809          'description' => $project->getDescription(),
 810          'show_description_in_overview' => $project->getShowDescriptionInOverview()
 811        ); // array
 812      } // if
 813      
 814      $page_attachments = PageAttachments::getAttachmentsByPageNameAndProject($page_name, $project);
 815
 816      $redirect_to = urldecode(array_var($_GET, 'redirect_to'));
 817      
 818      tpl_assign('project', $project);
 819      tpl_assign('project_data', $project_data);
 820      tpl_assign('page_attachments', $page_attachments);
 821      tpl_assign('redirect_to', $redirect_to);
 822      
 823      if (is_array(array_var($_POST, 'project'))) {
 824        $project->setFromAttributes($project_data);
 825        
 826        try {
 827          DB::beginWork();
 828          $project->save();
 829          ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_EDIT, false, true);
 830
 831          $page_attachments = array_var($project_data, 'page_attachments');
 832          if (is_array($page_attachments)) {
 833            foreach ($page_attachments as $id => $page_attachment_data) {
 834              $page_attachment = PageAttachments::findById($id);
 835              if (array_var($page_attachment_data, 'delete') == "checked") {
 836                $page_attachment->delete();
 837              } else {
 838                $page_attachment->setFromAttributes($page_attachment_data);
 839                $page_attachment->save();
 840              } // if
 841            } // foreach
 842            PageAttachments::reorder($page_name, $project);
 843          } // if
 844          DB::commit();
 845          
 846          flash_success(lang('success edit project', $project->getName()));
 847          if ((trim($redirect_to)) == '' || !is_valid_url($redirect_to)) {
 848            $redirect_to = $project->getSettingsUrl();
 849          } // if
 850          $this->redirectToUrl($redirect_to);
 851
 852        } catch(Exception $e) {
 853          DB::rollback();
 854          tpl_assign('error', $e);
 855        } // try
 856      } // if
 857    } // edit
 858
 859    /**
 860    * Show and process edit project logo form
 861    *
 862    * @param void
 863    * @return null
 864    */
 865    function edit_logo() {
 866      $project = Projects::findById(get_id());
 867      if (!($project instanceof Project)) {
 868        flash_error(lang('project dnx'));
 869        $this->redirectToReferer(get_url('dashboard'));
 870      } // if
 871
 872      if (!$project->canEdit(logged_user())) {
 873        flash_error(lang('no access permissions'));
 874        $this->redirectToReferer(get_url('dashboard'));
 875      } // if
 876
 877      if (!function_exists('imagecreatefromjpeg')) {
 878        flash_error(lang('no image functions'));
 879        $this->redirectTo('dashboard');
 880      } // if
 881
 882      $this->setTemplate('edit_logo');
 883      $this->setLayout('administration');
 884      
 885      tpl_assign('project', $project);
 886      
 887      $logo = array_var($_FILES, 'new_logo');
 888
 889      if (is_array($logo)) {
 890        try {
 891          move_uploaded_file($logo["tmp_name"], ROOT . "/tmp/" . $logo["name"]);
 892          $logo["tmp_name"] = ROOT . "/tmp/" . $logo["name"];
 893          if (!isset($logo['name']) || !isset($logo['type']) || !isset($logo['size']) || !isset($logo['tmp_name']) || !is_readable($logo['tmp_name'])) {
 894            throw new InvalidUploadError($logo, lang('error upload file'));
 895          } // if
 896          
 897          $valid_types = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
 898          $max_width   = config_option('max_logo_width', 50);
 899          $max_height  = config_option('max_logo_height', 50);
 900          
 901          if (!in_array($logo['type'], $valid_types) || !($image = getimagesize($logo['tmp_name']))) {
 902            throw new InvalidUploadError($logo, lang('invalid upload type', 'JPG, GIF, PNG'));
 903          } // if
 904          
 905          $old_file = $project->getLogoPath();
 906          
 907          DB::beginWork();
 908          
 909          if (!$project->setLogo($logo['tmp_name'], $max_width, $max_height, true)) {
 910            DB::rollback();
 911            flash_error(lang('error edit project logo', $e));
 912            $this->redirectToUrl($project->getEditLogoUrl());
 913          } // if
 914          
 915          ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_EDIT);
 916          
 917          flash_success(lang('success edit project logo'));
 918          DB::commit();
 919          
 920          if (is_file($old_file)) {
 921            @unlink($old_file);
 922          } // uf
 923          
 924        } catch(Exception $e) {
 925          flash_error(lang('error edit project logo', $e));
 926          DB::rollback();
 927        } // try
 928        
 929        $this->redirectToUrl($project->getEditLogoUrl());
 930      } // if
 931    } // edit_logo
 932    
 933    /**
 934    * Delete company logo
 935    *
 936    * @param void
 937    * @return null
 938    */
 939    function delete_logo() {
 940      if (!logged_user()->isAdministrator(owner_company())) {
 941        flash_error(lang('no access permissions'));
 942        $this->redirectTo('dashboard');
 943      } // if
 944      
 945      $project = Projects::findById(get_id());
 946      if (!($project instanceof Project)) {
 947        flash_error(lang('project dnx'));
 948        $this->redirectToReferer(get_url('dashboard', 'projects'));
 949      } // if
 950      
 951      try {
 952        DB::beginWork();
 953        $project->deleteLogo();
 954        $project->save();
 955        ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_EDIT);
 956        DB::commit();
 957        
 958        flash_success(lang('success delete project logo'));
 959      } catch(Exception $e) {
 960        DB::rollback();
 961        flash_error(lang('error delete project logo'));
 962      } // try
 963      
 964      $this->redirectToUrl($project->getEditLogoUrl());
 965    } // delete_logo
 966    
 967    /**
 968    * Delete project
 969    *
 970    * @param void
 971    * @return null
 972    */
 973    function delete() {
 974      $this->setTemplate('del_project');
 975      $this->setLayout('administration');
 976
 977      $project = Projects::findById(get_id());
 978      if (!($project instanceof Project)) {
 979        flash_error(lang('project dnx'));
 980        $this->redirectTo('administration', 'projects');
 981      } // if
 982      
 983      if (!$project->canDelete(logged_user())) {
 984        flash_error(lang('no access permissions'));
 985        $this->redirectToReferer(get_url('administration', 'projects'));
 986      } // if
 987
 988      $delete_data = array_var($_POST, 'deleteProject');
 989      tpl_assign('project', $project);
 990      tpl_assign('delete_data', $delete_data);
 991
 992      if (!is_array($delete_data)) {
 993        $delete_data = array(
 994          'really' => 0,
 995          'password' => '',
 996          ); // array
 997        tpl_assign('delete_data', $delete_data);
 998      } else if ($delete_data['really'] == 1) {
 999        $password = $delete_data['password'];
1000        if (trim($password) == '') {
1001          tpl_assign('error', new Error(lang('password value missing')));
1002          $this->render();
1003        }
1004        if (!logged_user()->isValidPassword($password)) {
1005          tpl_assign('error', new Error(lang('invalid login data')));
1006          $this->render();
1007        } // if
1008        try {
1009
1010          DB::beginWork();
1011          $project->delete();
1012          CompanyWebsite::instance()->setProject(null);
1013          ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_DELETE);
1014          DB::commit();
1015
1016          flash_success(lang('success delete project', $project->getName()));
1017
1018        } catch(Exception $e) {
1019          DB::rollback();
1020          flash_error(lang('error delete project'));
1021        } // try
1022
1023        $this->redirectTo('administration', 'projects');
1024      } else {
1025        flash_error(lang('error delete project'));
1026        $this->redirectTo('administration', 'projects');
1027      }
1028    } // delete
1029    
1030    /**
1031    * Complete this project
1032    *
1033    * @param void
1034    * @return null
1035    */
1036    function complete() {
1037      
1038      $project = Projects::findById(get_id());
1039      if (!($project instanceof Project)) {
1040        flash_error(lang('project dnx'));
1041        $this->redirectTo('administration', 'projects');
1042      } // if
1043      
1044      if (!$project->canChangeStatus(logged_user())) {
1045        flash_error(lang('no access permissions'));
1046        $this->redirectToReferer(get_url('administration', 'projects'));
1047      } // if
1048      
1049      try {
1050        
1051        $project->setCompletedOn(DateTimeValueLib::now());
1052        $project->setCompletedById(logged_user()->getId());
1053        
1054        DB::beginWork();
1055        $project->save();
1056        ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_CLOSE);
1057        DB::commit();
1058        
1059        flash_success(lang('success complete project', $project->getName()));
1060        
1061      } catch(Exception $e) {
1062        DB::rollback();
1063        flash_error(lang('error complete project'));
1064      } // try
1065      
1066      $this->redirectToReferer(get_url('administration', 'projects'));
1067    } // complete
1068    
1069    /**
1070    * Reopen project
1071    *
1072    * @param void
1073    * @return null
1074    */
1075    function open() {
1076      $project = Projects::findById(get_id());
1077      if (!($project instanceof Project)) {
1078        flash_error(lang('project dnx'));
1079        $this->redirectTo('administration', 'projects');
1080      } // if
1081      
1082      if (!$project->canChangeStatus(logged_user())) {
1083        flash_error(lang('no access permissions'));
1084        $this->redirectToReferer(get_url('administration', 'projects'));
1085      } // if
1086      
1087      try {
1088        
1089        $project->setCompletedOn(null);
1090        $project->setCompletedById(0);
1091        
1092        DB::beginWork();
1093        $project->save();
1094        ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_OPEN);
1095        DB::commit();
1096        
1097        flash_success(lang('success open project', $project->getName()));
1098        
1099      } catch(Exception $e) {
1100        DB::rollback();
1101        flash_error(lang('error open project'));
1102      } // try
1103      
1104      $this->redirectToReferer(get_url('administration', 'projects'));
1105    } // open
1106    
1107    
1108    /**
1109    * Adds contact to project (as a PageAttachment)
1110    *
1111    * @param void
1112    * @return null
1113    */
1114    function add_contact() {
1115      if (!active_project()->canChangePermissions(logged_user())) {
1116        flash_error(lang('no access permissions'));
1117        $this->redirectToReferer(active_project()->getOverviewUrl());
1118      } // if
1119      
1120      $already_attached_contacts = PageAttachments::getAttachmentsByTypeAndProject(array('Contacts'), active_project());
1121      $already_attached_contacts_ids = null;
1122      if (is_array($already_attached_contacts)) {
1123        $already_attached_contacts_ids = array();
1124        foreach ($already_attached_contacts as $already_attached_contact) {
1125          $already_attached_contacts_ids[] = $already_attached_contact->getRelObjectId();
1126        } // foreach
1127      } // if
1128      
1129      $this->setTemplate('add_contact');
1130      
1131      $contact = new Contact();
1132      
1133      $im_types = ImTypes::findAll(array('order' => '`id`'));
1134
1135      $contact_data = array_var($_POST, 'contact');
1136      if (!is_array($contact_data)) {
1137        $contact_data = array(); // array
1138      } // if
1139      
1140      $existing_contact_data = array_var($contact_data, 'existing');
1141      if (!is_array($existing_contact_data)) {
1142        $existing_contact_data = array(); // array
1143      } // if
1144      $new_contact_data = array_var($contact_data, 'new');
1145      if (!is_array($new_contact_data)) {
1146        $new_contact_data = array(); // array
1147      } // if
1148      $company_data = array_var($new_contact_data, 'company');
1149      if (!is_array($company_data)) {
1150        $company_data = array(); // array
1151      } // if
1152      $user_data = array_var($new_contact_data, 'user');
1153      if (!is_array($user_data)) {
1154        $user_data = array(); // array
1155      } // if
1156      
1157      $project_init = array_var($_GET, 'project_init');
1158      
1159      tpl_assign('already_attached_contacts_ids', $already_attached_contacts_ids);
1160      tpl_assign('contact', $contact);
1161      tpl_assign('contact_data', $contact_data);
1162      tpl_assign('existing_contact_data', $existing_contact_data);
1163      tpl_assign('new_contact_data', $new_contact_data);
1164      tpl_assign('company_data', $company_data);
1165      tpl_assign('user_data', $user_data);
1166      tpl_assign('project_init', $project_init);
1167      tpl_assign('im_types', $im_types);
1168      tpl_assign('project', active_project());
1169
1170      if (is_array(array_var($_POST, 'contact'))) {
1171        if (array_var($contact_data, 'what') == 'existing') {
1172          if (!(Contacts::findById(array_var($existing_contact_data, 'rel_object_id')) instanceof Contact)) {
1173            tpl_assign('error', new FormSubmissionErrors(array(lang('existing contact required'))));
1174          } else {
1175            $page_attachment = new PageAttachment();
1176            $page_attachment->setFromAttributes($existing_contact_data);
1177            $page_attachment->setRelObjectManager('Contacts');
1178            $page_attachment->setProjectId(active_project()->getId());
1179            $page_attachment->setPageName('people');
1180            $page_attachment->save();
1181            PageAttachments::reorder('people', active_project());
1182            flash_success(lang('success add contact', $page_attachment->getObject()->getDisplayName()));
1183            if ($project_init) {
1184              $this->redirectToUrl(active_project()->getAddContactUrl(array('project_init' => '1')));
1185            } else {
1186              $this->redirectToUrl(get_url('project', 'people'));
1187            } // if
1188          } // if
1189        } else {
1190          // New contact
1191          // Save avatar
1192          $avatar = array_var($_FILES, 'new_avatar');
1193          if (is_array($avatar) && isset($avatar['size']) && $avatar['size'] != 0) {
1194            try {
1195              if (!isset($avatar['name']) || !isset($avatar['type']) || !isset($avatar['size']) || !isset($avatar['tmp_name']) || !is_readable($avatar['tmp_name'])) {
1196                throw new InvalidUploadError($avatar, lang('error upload file'));
1197              } // if
1198
1199              $valid_types = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
1200              $max_width   = config_option('max_avatar_width', 50);
1201              $max_height  = config_option('max_avatar_height', 50);
1202
1203              if ($avatar['size']) {
1204                if (!in_array($avatar['type'], $valid_types) || !($image = getimagesize($avatar['tmp_name']))) {
1205                  throw new InvalidUploadError($avatar, lang('invalid upload type', 'JPG, GIF, PNG'));
1206                } elseif (!$contact->setAvatar($avatar['tmp_name'], $max_width, $max_height, false)) {
1207                  throw new Error($avatar, lang('error edit avatar'));
1208                  $contact->setAvatarFile('');
1209                } // if
1210              } // if
1211            } catch (Exception $e) {
1212              flash_error($e->getMessage());
1213            }
1214          } else {
1215            $contact->setAvatarFile('');
1216          } // if
1217          
1218          try {
1219            DB::beginWork();
1220            $contact->setFromAttributes($new_contact_data);
1221            
1222            if (array_var($company_data, 'what') == 'existing') {
1223              $company_id = $new_contact_data['company_id'];
1224            } else {
1225              $company = new Company();
1226              $company->setName(array_var($company_data, 'name'));
1227              $company->setTimezone(array_var($company_data, 'timezone'));
1228              $company->setClientOfId(owner_company()->getId());
1229              $company->save();
1230              $company_id = $company->getId();
1231            } // if
1232            $contact->setCompanyId($company_id);
1233
1234            // User account info
1235            if (array_var($user_data, 'add_account') == "yes") {
1236              $user = new User();
1237              $user->setFromAttributes($user_data);
1238
1239              if (array_var($user_data, 'password_generator') == 'random') {
1240                // Generate random password
1241                $password = substr(sha1(uniqid(rand(), true)), rand(0, 25), 13);
1242              } else {
1243                // Validate user input
1244                $password = array_var($user_data, 'password');
1245                if (trim($password) == '') {
1246                  throw new Error(lang('password value required'));
1247                } // if
1248                if ($password <> array_var($user_data, 'password_a')) {
1249                  throw new Error(lang('passwords dont match'));
1250                } // if
1251              } // if
1252              $user->setPassword($password);
1253              $user->save();
1254
1255              $contact->setUserId($user->getId());
1256            } else {
1257              $contact->setUserId(0);
1258            } // if
1259
1260            $contact->save();
1261            if (plugin_active('tags')) {
1262              $contact->setTagsFromCSV(array_var($new_contact_data, 'tags'));
1263            }
1264
1265            $contact->clearImValues();
1266            foreach ($im_types as $im_type) {
1267              $value = trim(array_var($new_contact_data, 'im_' . $im_type->getId()));
1268              if ($value <> '') {
1269
1270                $contact_im_value = new ContactImValue();
1271
1272                $contact_im_value->setContactId($contact->getId());
1273                $contact_im_val…

Large files files are truncated, but you can click here to view the full file