/**
  * Process the form to edit an existing test session.
  *
  * @param sfWebRequest $request
  * @param SessionForm $form
  */
 protected function processEdit(sfWebRequest $request, SessionForm $form)
 {
     $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
     if ($form->isValid()) {
         $qa_generic = sfConfig::get("app_table_qa_generic");
         // Get sent values and uploaded files
         $values = $form->getValues();
         $files = $request->getFiles();
         // Retrieve values from form
         $projectGroupId = $values["project_group_id"];
         $projectId = $values["project"];
         $productId = $values["product"];
         // Get test environment and image names
         $environmentForm = $form->getValue("environmentForm");
         $imageForm = $form->getValue("imageForm");
         // Create a new relationship between project group, project and product if needed
         $projectToProductId = Doctrine_Core::getTable("ProjectToProduct")->getProjectToProductId($projectGroupId, $projectId, $productId);
         if ($projectToProductId == null) {
             $projectToProduct = new ProjectToProduct();
             $projectToProduct->setProjectGroupId($projectGroupId);
             $projectToProduct->setProjectId($projectId);
             $projectToProduct->setProductId($productId);
             $projectToProduct->save($conn);
             $projectToProductId = $projectToProduct->getId();
         }
         // Create a new environment if needed
         $environment = Doctrine_Core::getTable("TestEnvironment")->findByArray($environmentForm);
         if ($environment == null) {
             // Add new environment
             $environment = new TestEnvironment();
             $environment->setName($environmentForm["name"]);
             $environment->setDescription($environmentForm["description"]);
             $environment->setCpu($environmentForm["cpu"]);
             $environment->setBoard($environmentForm["board"]);
             $environment->setGpu($environmentForm["gpu"]);
             $environment->setOtherHardware($environmentForm["other_hardware"]);
             // Check if its slug does not already exist and generate a new one if needed
             $slug = MiscUtils::slugify($environmentForm["name"]);
             $size = 1;
             while (Doctrine_Core::getTable("TestEnvironment")->checkSlug($slug)) {
                 $slug = MiscUtils::slugify($environmentForm["name"]) . substr(microtime(), -$size);
                 $size++;
             }
             $environment->setNameSlug($slug);
             $environment->save($conn);
             // Convert object into associative array
             $environment = $environment->toArray();
         }
         // Create a new image if needed
         $image = Doctrine_Core::getTable("Image")->findByArray($imageForm);
         if ($image == null) {
             // Add new image
             $image = new Image();
             $image->setName($imageForm["name"]);
             $image->setDescription($imageForm["description"]);
             $image->setOs($imageForm["os"]);
             $image->setDistribution($imageForm["distribution"]);
             $image->setVersion($imageForm["version"]);
             $image->setKernel($imageForm["kernel"]);
             $image->setArchitecture($imageForm["architecture"]);
             $image->setOtherFw($imageForm["other_fw"]);
             $image->setBinaryLink($imageForm["binary_link"]);
             $image->setSourceLink($imageForm["source_link"]);
             // Check if its slug does not already exist and generate a new one if needed
             $slug = MiscUtils::slugify($imageForm["name"]);
             $size = 1;
             while (Doctrine_Core::getTable("Image")->checkSlug($slug)) {
                 $slug = MiscUtils::slugify($imageForm["name"]) . substr(microtime(), -$size);
                 $size++;
             }
             $image->setNameSlug(MiscUtils::slugify($slug));
             $image->save($conn);
             // Convert object into associative array
             $image = $image->toArray();
         }
         // Create a new configuration relationship if needed
         $configurationId = Doctrine_Core::getTable("Configuration")->getConfigurationId($projectToProductId, $environment["id"], $image["id"]);
         if ($configurationId == null) {
             $configuration = new Configuration();
             $configuration->setProjectToProductId($projectToProductId);
             $configuration->setTestEnvironmentId($environment["id"]);
             $configuration->setImageId($image["id"]);
             $configuration->save($conn);
             $configurationId = $configuration->getId();
         }
         // Edit the session into DB
         $testSession = Doctrine_Core::getTable("TestSession")->find($values["id"]);
         $testSession->setId($values["id"]);
         $testSession->setBuildId($values["build_id"]);
         $testSession->setTestset($values["testset"]);
         $testSession->setName($values["name"]);
         $testSession->setTestObjective($values["test_objective"]);
         $testSession->setQaSummary($values["qa_summary"]);
         $testSession->setUserId($values["user_id"]);
         $testSession->setCreatedAt($values["created_at"]);
         $testSession->setEditorId($values["editor_id"]);
         $testSession->setUpdatedAt($values["updated_at"]);
         $testSession->setProjectRelease($values["project_release"]);
         $testSession->setProjectMilestone($values["project_milestone"]);
         $testSession->setIssueSummary($values["issue_summary"]);
         $testSession->setStatus($values["status"]);
         $testSession->setPublished($values["published"]);
         $testSession->setConfigurationId(intval($configurationId));
         $testSession->setCampaignChecksum($values["campaign_checksum"]);
         $testSession->setBuildSlug(MiscUtils::slugify($values["build_id"]));
         $testSession->setTestsetSlug(MiscUtils::slugify($values["testset"]));
         $testSession->setNotes($values["notes"]);
         $testSession->save();
         $testSessionId = $values["id"];
         // Get all results (and add associative key for each result)
         $array = array();
         foreach (Doctrine_Core::getTable("TestSession")->getSessionResults($this->currentSession["id"]) as $key => $value) {
             $array[MiscUtils::slugify($value["label"]) . $value["id"]] = $value;
         }
         $results = $array;
         // Get all measures (and add associative key for each measure)
         $array = array();
         foreach (Doctrine_Core::getTable("TestSession")->getSessionMeasures($this->currentSession["id"]) as $key => $value) {
             $array[MiscUtils::slugify($value["label"]) . $value["id"]] = $value;
         }
         $measures = $array;
         // Save test results
         foreach ($results as $key => $result) {
             if (array_key_exists($key, $values)) {
                 $resultForm = Doctrine_Core::getTable("TestResult")->find($result["id"]);
                 $resultForm->setId($result["id"]);
                 $resultForm->setDecisionCriteriaId($values[$key]["decision_criteria_id"]);
                 $resultForm->setComment($values[$key]["comment"]);
                 $resultForm->save();
             }
         }
         // Save measures
         foreach ($measures as $key => $measure) {
             if (array_key_exists($key, $values)) {
                 $resultForm = Doctrine_Core::getTable("TestResult")->find($measure["id"]);
                 $resultForm->setId($measure["id"]);
                 $resultForm->setDecisionCriteriaId($values[$key]["decision_criteria_id"]);
                 $resultForm->setComment($values[$key]["comment"]);
                 $resultForm->save();
             }
         }
         // Get project and product name slug
         $projectSlug = Doctrine_Core::getTable("Project")->getSlugById($projectId);
         $productSlug = Doctrine_Core::getTable("ProductType")->getSlugById($productId);
         // Retrieve table_name_test_session_id from table_name
         $tableName = Doctrine_Core::getTable("TableName")->findOneByName("test_session");
         $tableNameTestSessionId = $tableName->getId();
         // Import attachments and result files
         foreach ($files["attachments"] as $key => $file) {
             if ($file["error"] != UPLOAD_ERR_NO_FILE) {
                 $fileName = $file['name'];
                 $fileSize = $file['size'];
                 $fileType = $file['type'];
                 $fileError = $file['error'];
                 $fileChecksum = sha1_file($file["tmp_name"]);
                 // Check file error and file size (5Mo max)
                 if (!$fileError and $fileSize <= 5000000) {
                     // Concatenate destination path
                     $dest_path = sfConfig::get('sf_upload_dir') . "/testsession_" . $testSessionId;
                     if (!is_dir($dest_path)) {
                         mkdir($dest_path, 0777, true);
                     }
                     $dest_path .= "/" . $fileName;
                     // Move file to uploads directory
                     move_uploaded_file($file['tmp_name'], $dest_path);
                     $web_path = "/uploads" . "/testsession_" . $testSessionId . "/" . $fileName;
                     $fileAttachment = new FileAttachment();
                     $fileAttachment->setName($fileName);
                     $fileAttachment->setUserId($this->getUser()->getGuardUser()->getId());
                     $fileAttachment->setUploadedAt(date("Y-m-d H:i:s"));
                     $fileAttachment->setFilename($fileName);
                     $fileAttachment->setFileSize($fileSize);
                     $fileAttachment->setFileMimeType($fileType);
                     $fileAttachment->setLink($web_path);
                     $fileAttachment->setChecksum($fileChecksum);
                     $fileAttachment->setTableNameId($tableNameTestSessionId);
                     $fileAttachment->setTableEntryId($testSessionId);
                     $fileAttachment->setCategory(2);
                     $fileAttachment->save();
                 }
             }
         }
         // Customize database connection to begin a transactionnal query
         $conn = Doctrine_Manager::getInstance()->getConnection("qa_generic");
         $conn->setAttribute(Doctrine_Core::ATTR_AUTOCOMMIT, FALSE);
         $conn->beginTransaction();
         // Get file attachments id into an array
         $fileAttachmentIdList = array();
         $query = "SELECT fa.id\n\t\t\t\t\tFROM " . $qa_generic . ".file_attachment fa\n\t\t\t\t\tWHERE fa.table_entry_id = " . $testSessionId . "\n\t\t\t\t\t\tAND fa.table_name_id = " . $tableNameTestSessionId;
         $results = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetchAll(PDO::FETCH_ASSOC);
         foreach ($results as $result) {
             $fileAttachmentIdList[] = $result["id"];
         }
         $fileAttachmentIdStringList = implode(",", $fileAttachmentIdList);
         // Concatenate directory path
         $dir_path = sfConfig::get('sf_upload_dir') . "/testsession_" . $testSessionId;
         $fileAttachmentResultIds = array();
         $similarFileFound = false;
         foreach ($files["result_files"] as $key => $file) {
             if ($file["error"] != UPLOAD_ERR_NO_FILE) {
                 $reportType = false;
                 $fileName = $file['name'];
                 $fileSize = $file['size'];
                 $fileType = $file['type'];
                 $fileError = $file['error'];
                 $fileChecksum = sha1_file($file["tmp_name"]);
                 $query = "SELECT fa.id\n\t\t\t\t\t\t\tFROM " . $qa_generic . ".file_attachment fa\n\t\t\t\t\t\t\tWHERE fa.table_entry_id = " . $testSessionId . "\n\t\t\t\t\t\t\t\tAND fa.table_name_id = " . $tableNameTestSessionId . "\n\t\t\t\t\t\t\t\tAND fa.checksum = '" . $fileChecksum . "'";
                 $result = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetch(PDO::FETCH_ASSOC);
                 if (!empty($result["id"])) {
                     $fileAttachmentResultIds[] = $result["id"];
                     $similarFileFound = true;
                 }
                 // Check file error and file size
                 if (!$fileError and $fileSize <= sfConfig::get('app_max_file_size', '10000000')) {
                     if (!is_dir($dir_path)) {
                         mkdir($dir_path, 0777, true);
                     }
                     $dest_path = $dir_path . "/" . $fileName;
                     $idx = 0;
                     while (is_file($dest_path)) {
                         $idx++;
                         $dest_path = $dir_path . "/" . "(" . $idx . ")" . $fileName;
                     }
                     // Move file to uploads directory
                     move_uploaded_file($file['tmp_name'], $dest_path);
                     if ($idx == 0) {
                         $web_path = "/uploads" . "/testsession_" . $testSessionId . "/" . $fileName;
                     } else {
                         $web_path = "/uploads" . "/testsession_" . $testSessionId . "/" . "(" . $idx . ")" . $fileName;
                     }
                     $fileAttachment = new FileAttachment();
                     $fileAttachment->setName($fileName);
                     $fileAttachment->setUserId($this->getUser()->getGuardUser()->getId());
                     $fileAttachment->setUploadedAt(date("Y-m-d H:i:s"));
                     $fileAttachment->setFilename($fileName);
                     $fileAttachment->setFileSize($fileSize);
                     $fileAttachment->setFileMimeType($fileType);
                     $fileAttachment->setLink($web_path);
                     $fileAttachment->setChecksum($fileChecksum);
                     $fileAttachment->setTableNameId($tableNameTestSessionId);
                     $fileAttachment->setTableEntryId($testSessionId);
                     if (preg_match("#\\.xml\$#i", $fileName) | preg_match("#\\.csv\$#i", $fileName)) {
                         $reportType = true;
                         $fileAttachment->setCategory(1);
                     } else {
                         $fileAttachment->setCategory(2);
                     }
                     $fileAttachment->save($conn);
                     // If it is an XML or CSV file, parse it and fill qa_generic database
                     if ($reportType) {
                         if ($err_code = Import::file($dest_path, $testSessionId, $configurationId, $conn, true)) {
                             // Delete new files
                             $query = "SELECT fa.link\n\t\t\t\t\t\t\t\t\t\tFROM " . $qa_generic . ".file_attachment fa\n\t\t\t\t\t\t\t\t\t\tWHERE fa.table_entry_id = " . $testSessionId . "\n\t\t\t\t\t\t\t\t\t\t\tAND fa.table_name_id = " . $tableNameTestSessionId . "\n\t\t\t\t\t\t\t\t\t\t\tAND fa.id NOT IN (" . $fileAttachmentIdStringList . ")";
                             $results = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetchAll(PDO::FETCH_ASSOC);
                             foreach ($results as $result) {
                                 unlink(sfConfig::get('sf_web_dir') . $result["link"]);
                             }
                             $error_message = Import::getImportErrorMessage($err_code);
                             $conn->rollback();
                             $conn->setAttribute(Doctrine_Core::ATTR_AUTOCOMMIT, TRUE);
                             $this->getUser()->setFlash("error", "Invalid file content on " . $fileName . " : " . $error_message);
                             $this->redirect("edit_report", array("project" => $projectSlug, "product" => $productSlug, "environment" => $environment["name_slug"], "image" => $image["name_slug"], "id" => $testSessionId));
                         }
                     }
                 } else {
                     // Delete new files
                     $query = "SELECT fa.link\n\t\t\t\t\t\t\t\tFROM " . $qa_generic . ".file_attachment fa\n\t\t\t\t\t\t\t\tWHERE fa.table_entry_id = " . $testSessionId . "\n\t\t\t\t\t\t\t\t\tAND fa.table_name_id = " . $tableNameTestSessionId . "\n\t\t\t\t\t\t\t\t\tAND fa.id NOT IN (" . $fileAttachmentIdStringList . ")";
                     $results = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetchAll(PDO::FETCH_ASSOC);
                     foreach ($results as $result) {
                         unlink(sfConfig::get('sf_web_dir') . $result["link"]);
                     }
                     $conn->rollback();
                     $conn->setAttribute(Doctrine_Core::ATTR_AUTOCOMMIT, TRUE);
                     $this->getUser()->setFlash("error", "File size limit reached");
                     $this->redirect("edit_report", array("project" => $projectSlug, "product" => $productSlug, "environment" => $environment["name_slug"], "image" => $image["name_slug"], "id" => $testSessionId));
                 }
             }
         }
         if ($similarFileFound) {
             $fileAttachmentStringResultIds = implode(",", $fileAttachmentResultIds);
             // Delete similar files and attachment entries
             $query = "SELECT fa.id, fa.link\n\t\t\t\t\t\tFROM " . $qa_generic . ".file_attachment fa\n\t\t\t\t\t\tWHERE fa.table_entry_id = " . $testSessionId . "\n\t\t\t\t\t\t\tAND fa.table_name_id = " . $tableNameTestSessionId . "\n\t\t\t\t\t\t\tAND fa.id IN (" . $fileAttachmentStringResultIds . ")";
             $results = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetchAll(PDO::FETCH_ASSOC);
             foreach ($results as $result) {
                 unlink(sfConfig::get('sf_web_dir') . $result["link"]);
                 Doctrine_Core::getTable("FileAttachment")->deleteFileAttachmentById($result["id"], $conn);
             }
         }
         $conn->commit();
         $conn->setAttribute(Doctrine_Core::ATTR_AUTOCOMMIT, TRUE);
         // 			// Clear cache for actions related to this test session
         // 			$cacheManager = $this->getContext()->getViewCacheManager();
         // 			$cacheManager->remove("reports/session?project=".$projectSlug."&product=".$productSlug."&environment=".$environment["name_slug"]."&image=".$image["name_slug"]."?id=".$testSession["id"]);
         // Set flash for user and redirect to session display
         $this->getUser()->setFlash("notice", "Test session was updated successfully");
         if (!empty($testSession["build_slug"])) {
             $this->redirect("build_session", array("project" => $projectSlug, "product" => $productSlug, "build" => $testSession["build_slug"], "environment" => $environment["name_slug"], "image" => $image["name_slug"], "id" => $request->getParameter("id")));
         } else {
             $this->redirect("test_session", array("project" => $projectSlug, "product" => $productSlug, "environment" => $environment["name_slug"], "image" => $image["name_slug"], "id" => $request->getParameter("id")));
         }
     }
 }
 protected function processUpdate(sfWebRequest $request, ProjectFormCustom $form)
 {
     $qa_generic = sfConfig::get("app_table_qa_generic");
     $form->bind($request->getParameter($form->getName()));
     if ($form->isValid()) {
         $values = $form->getValues();
         // Get project and project group id
         $projectId = $values['id'];
         $projectGroupId = $values['group'];
         // Slugify name, check if generated slug does not already exist and generate a new one if needed
         if (empty($values['name_slug'])) {
             $slug = MiscUtils::slugify($values['name']);
         } else {
             $slug = $values['name_slug'];
         }
         $size = 1;
         while (Doctrine_Core::getTable("Project")->checkSlugForProject($projectId, $slug, false)) {
             $slug = MiscUtils::slugify($values['name']) . substr(microtime(), -$size);
             $size++;
         }
         // Update project data
         $projectObject = Doctrine_Core::getTable('Project')->find($projectId);
         $projectObject->setName($values['name']);
         $projectObject->setDescription($values['description']);
         $projectObject->setUserId($values['user_id']);
         $projectObject->setCreatedAt($values['created_at']);
         $projectObject->setStatus($values['status']);
         $projectObject->setSecurityLevel($values['security_level']);
         $projectObject->setNameSlug($slug);
         $projectObject->save();
         // Get all products linked to the current project from the database (complementary_tool_relation table)
         $query = "SELECT ptp.id, ptp.product_id FROM " . $qa_generic . ".project_to_product ptp WHERE ptp.project_id = " . $projectId . " AND ptp.project_group_id = " . $projectGroupId;
         $results = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($query)->fetchAll(PDO::FETCH_ASSOC);
         $productsFromDatabase = array();
         foreach ($results as $projectToProduct) {
             // If one of the retrieved relationship is missing from form's products, delete the entry from database
             if (!in_array($projectToProduct['product_id'], $values['product'])) {
                 Doctrine_Core::getTable('ProjectToProduct')->delete($projectToProduct['id']);
             } else {
                 array_push($productsFromDatabase, $projectToProduct['product_id']);
             }
         }
         // Now, cycle through form's products to add the new entries
         foreach ($values['product'] as $product) {
             if (!in_array($product, $productsFromDatabase)) {
                 // Create new entry into ProjectToProduct table
                 $ptpObject = new ProjectToProduct();
                 $ptpObject->setProjectGroupId($values['group']);
                 $ptpObject->setProjectId($projectId);
                 $ptpObject->setProductId($product);
                 $ptpObject->save();
             }
         }
         $this->getUser()->setFlash('notice', 'Project has been updated');
         $this->redirect(array('sf_route' => 'project_edit', 'sf_subject' => $projectObject));
     } else {
         $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
     }
 }