function save_document() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		ajx_current("empty");
		$postFile = array_var($_POST, 'file');
		$fileId = array_var($postFile, 'id');
		if($fileId > 0) {
			//edit document
			try {
				$file = ProjectFiles::findById($fileId);
				if (!$file->canEdit(logged_user())) {
					flash_error(lang('no access permissions'));
					ajx_current("empty");
					return;
				} // if
				$file_content = array_var($_POST, 'fileContent');
				if ($file_content == $file->getFileContent()){
					flash_error(lang('there are no changes'));
				}else{
				DB::beginWork();
				$post_revision = array_var($_POST, 'new_revision_document') == 'checked'; // change file?
				$revision_comment = array_var($postFile, 'comment');

				$file_content = array_var($_POST, 'fileContent');
				$image_file_ids = array();
				preg_match_all("/<img[^>]*src=[\"']([^\"']*)[\"']/", $file_content, $matches);
				$urls = array_var($matches, 1);
				if (is_array($urls)) {
					$img_num = 1;
					foreach ($urls as $url) {
						if (strpos(html_entity_decode($url), get_url('files', 'download_image')) === false ) {
							$img_file_id = self::upload_document_image($url, $file->getFilename(), $img_num);
							$file_content = str_replace($url, get_url('files', 'download_image', array('id' => $img_file_id, 'inline' => 1)) , $file_content);
							$image_file_ids[] = $img_file_id;
						}
						$img_num++;
					}
				}
				
				$file_dt['name'] = $file->getFilename();
				$file_dt['size'] = strlen($file_content);
				$file_dt['type'] = array_var($_POST, 'fileMIME', 'text/html');
				$file_dt['tmp_name'] = ROOT . '/tmp/' . rand () ;
				$handler = fopen($file_dt['tmp_name'], 'w');
				fputs($handler,$file_content);
				fclose($handler);
				$name = array_var($postFile, 'name');

				$file->setFilename($name);
				$file->save();
				$file->handleUploadedFile($file_dt, $post_revision, $revision_comment);
				
				if (array_var($_POST, 'checkin', false)) {
					$file->checkIn();
					ajx_current("back");
				}
				
				$object_controller = new ObjectController();
				$file_member_ids = $file->getMemberIds();
				if (count($image_file_ids) > 0) {
					$image_files = ProjectFiles::findAll(array('conditions' => 'id IN ('.implode(',',$image_file_ids).')'));
					foreach ($image_files as $img_file) {
						$object_controller->add_to_members($img_file, $file_member_ids, null, false);
						$img_file->setMailId($file->getId());
						$img_file->save();
					}
				}
				
				//subscribe user if not subscribed
				if(!$file->isSubscriber(logged_user())) {
					$file->subscribeUser(logged_user());
				} // if
				
				
				ApplicationLogs::createLog($file, ApplicationLogs::ACTION_EDIT);
				DB::commit();
				unlink($file_dt['tmp_name']);

				flash_success(lang('success save file', $file->getFilename()));
				evt_add("document saved", array("id" => $file->getId(), "instance" => array_var($_POST, 'instanceName')));
				
				ajx_add("overview-panel", "reload");
			}
			} catch(Exception $e) {
				DB::rollback();
				if (array_var($file_dt, 'tmp_name') && is_file(array_var($file_dt, 'tmp_name'))) {
					unlink(array_var($file_dt, 'tmp_name'));
				}
				flash_error(lang('error while saving'), $e->getMessage());
				
			} // try
		} else  {
			// new document
			$notAllowedMember = '';
			if (!ProjectFile::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("documents"),$notAllowedMember));
				ajx_current("empty");
				return ;
			} // if
			
			// prepare the file object
			$file = new ProjectFile();
			$name = array_var($postFile, 'name');
			$file->setObjectTypeId($file->getObjectTypeId());
			$file->setFilename($name);
			$file->setIsVisible(true);
			
			
			//seteo esto para despues setear atributos
			$file_content = array_var($_POST, 'fileContent');
			$image_file_ids = array();
			preg_match_all("/<img[^>]*src=[\"']([^\"']*)[\"']/", $file_content, $matches);
			$urls = array_var($matches, 1);
			if (is_array($urls)) {
				$img_num = 1;
				foreach ($urls as $url) {
					if (strpos($url, get_url('files', 'download_image')) === false ) {
						$img_file_id = self::upload_document_image($url, $file->getFilename(), $img_num);
						$file_content = str_replace($url, get_url('files', 'download_image', array('id' => $img_file_id, 'inline' => 1)) , $file_content);
						$image_file_ids[] = $img_file_id;
					}
					$img_num++;
				}
			}
			
			$file_dt['name'] = array_var($postFile,'name');
			$file_dt['size'] = strlen($file_content);
			$file_dt['type'] = array_var($_POST, 'fileMIME', 'text/html');

			$file->setCreatedOn(new DateTimeValue(time()) );
			try {
				DB::beginWork();
				$file_dt['tmp_name'] = ROOT . '/tmp/' . rand ();
				$handler = fopen($file_dt['tmp_name'], 'w');
				fputs($handler, array_var($_POST, 'fileContent'));
				fclose($handler);

				$revision_comment = array_var($postFile, 'comment');
				
				$file->save();
				$file->subscribeUser(logged_user());
				$revision = $file->handleUploadedFile($file_dt, true, $revision_comment); //FIXME

				if (config_option('checkout_for_editing_online')) {
					$file->checkOut(true, logged_user());
				}
				
				$object_controller = new ObjectController();
				
				// file is added to current context members
				$member_ids = array();
				$selection = active_context();
				foreach ($selection as $member) {
					if ($member instanceof Member) $member_ids[] = $member->getId();
				}
				$object_controller->add_to_members($file, $member_ids);
				
				if (count($image_file_ids) > 0) {
					$image_files = ProjectFiles::findAll(array('conditions' => 'id IN ('.implode(',',$image_file_ids).')'));
					foreach ($image_files as $img_file) {
						$object_controller->add_to_members($img_file, $member_ids, null, false);
						$img_file->setMailId($file->getId());
						$img_file->save();
					}
				}
				
				ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD);

				DB::commit();
				flash_success(lang('success save file', $file->getObjectName()));
				evt_add("document saved", array("id" => $file->getId(), "instance" => array_var($_POST, 'instanceName')));
				evt_add("new document add save as button", array("id" => $file->getId(), "name" => clean($file->getFilename()), "genid" => array_var($_POST, 'instanceName')));
				unlink($file_dt['tmp_name']);
				
			} catch(Exception $e) {
				DB::rollback();

				unlink($file_dt['tmp_name']);
				// if we uploaded the file remove it from repository
				if	(isset($revision) && ($revision instanceof ProjectFileRevision) && FileRepository::isInRepository($revision->getRepositoryId())) {
					FileRepository::deleteFile($revision->getRepositoryId());
				}
				flash_error(lang('error while saving').": ".$e->getMessage());
			} // try
		}
	}
 function do_unclassify($main_email)
 {
     $conv_emails = MailContents::getMailsFromConversation($main_email);
     foreach ($conv_emails as $email) {
         try {
             DB::beginWork();
             //only get workspaces with R&W permissions
             $all_workspaces = ProjectUsers::getProjectsByUser(logged_user());
             $ws_ids = array();
             foreach ($all_workspaces as $ws) {
                 $has_ws_perm = logged_user()->hasProjectPermission($ws, ProjectUsers::CAN_WRITE_MAILS);
                 $has_gr_perm = false;
                 if (!$has_ws_perm) {
                     $groups = logged_user()->getGroups();
                     foreach ($groups as $group) {
                         $has_gr_perm = $group->getProjectPermission($ws, ProjectUsers::CAN_WRITE_MAILS);
                     }
                 }
                 if ($has_ws_perm || $has_gr_perm) {
                     $ws_ids[] = $ws->getId();
                 }
             }
             $ws_ids = implode(',', $ws_ids);
             // remove workspaces
             $email->removeFromWorkspaces($ws_ids);
             // unclassify attachments, remove all allowed ws, then if file has no ws -> delete it
             if ($email->getHasAttachments()) {
                 MailUtilities::parseMail($email->getContent(), $decoded, $parsedEmail, $warnings);
                 if (isset($parsedEmail['Attachments'])) {
                     $files = ProjectFiles::findAll(array('conditions' => 'mail_id = ' . $email->getId()));
                     foreach ($files as $file) {
                         $file->removeFromWorkspaces($ws_ids);
                         $current_wss = $file->getWorkspaces();
                         if (!is_array($current_wss) || count($current_wss) == 0) {
                             $file->delete();
                         }
                     }
                 }
             }
             DB::commit();
             return true;
         } catch (Exception $e) {
             DB::rollback();
             return false;
         }
     }
 }
    /**
    * Restore project file revisions from attributes.php 
    * Use this when table ProjectFileRevisions is empty
    * @param void
    * @return null
    */
    function repair() {

      $attributes = include ROOT . '/upload/attributes.php';
      foreach ($attributes as $k => $v) {

        $files = ProjectFiles::findAll(array(
          'conditions' => array('`filename` = ?', $v['name'])
        )); // findAll
        foreach ($files as $file) {
          $id = $file->getId();
  
          $repository_id = $k;

          $revision = new ProjectFileRevision();
          $revision->setFileId($id);
          $revision->setRepositoryId($repository_id);
          $revision->deleteThumb(false);
          $revision->setFilesize($v['size']);
          $revision->setFilename($v['name']);
          $revision->setTypeString($v['type']);
      
          $extension = get_file_extension(basename($v['name']));
          if (trim($extension)) {
            $file_type = FileTypes::getByExtension($extension);
            if ($file_type instanceof Filetype) {
              $revision->setFileTypeId($file_type->getId());
            } // if
          } // if
      
          $revision->setComment('-- Initial version --');
          $revision->save();

        }
      }
      $this->redirectTo('files', 'index');
    }
 function addToMembers($members_array)
 {
     ObjectMembers::addObjectToMembers($this->getId(), $members_array);
     if ($this instanceof ProjectFile) {
         $inline_images = ProjectFiles::findAll(array("conditions" => "mail_id = " . $this->getId()));
         foreach ($inline_images as $inline_img) {
             $inline_img->addToMembers($members_array);
             $inline_img->addToSharingTable();
         }
     }
 }
Example #5
0
				$name = $newpath;
				$ext = "";
			} else {
				$name = substr($newpath, 0, $ext);
				$ext = substr($newpath, $ext + 1);
			}
			for ($i=2; file_exists($tmppath); $i++) {
				$tmppath = "$name-$i.$ext";
			}
			$newpath = $tmppath;
		}
		copy($path, $newpath);
		echo "Exported $filename\n";
	}
} else {
	$files = ProjectFiles::findAll();
	foreach ($files as $file) {
		$filename = $file->getFilename();
		$newpath = "tmp/export/" . $filename;
		if (file_exists($newpath)) {
			$tmppath = $newpath;
			$ext = strrpos($newpath, ".");
			if ($ext === false) {
				$name = $newpath;
				$ext = "";
			} else {
				$name = substr($newpath, 0, $ext);
				$ext = substr($newpath, $ext + 1);
			}
			for ($i=2; file_exists($tmppath); $i++) {
				$tmppath = "$name-$i.$ext";
	function addToMembers($members_array, $remove_old_comment_members = false){
		ObjectMembers::addObjectToMembers($this->getId(),$members_array);
		if ($this instanceof ProjectFile) {
			$inline_images = ProjectFiles::findAll(array("conditions" => "mail_id = ".$this->getId()));
			foreach ($inline_images as $inline_img) {
				$inline_img->addToMembers($members_array);
				$inline_img->addToSharingTable();
			}
		}
		if ($this->isCommentable()) {
			$comments = $this->getComments(true);
			foreach ($comments as $comment) {
				if ($remove_old_comment_members) {
					ObjectMembers::instance()->delete("object_id = ".$comment->getId());
				}
				$comment->addToMembers($members_array);
				$comment->addToSharingTable();
			}
		}
	}