Example #1
0
function mail_update_7_8()
{
    $sent_mails = MailContents::findAll(array('conditions' => "`state`=3 AND `has_attachments`=1"));
    foreach ($sent_mails as $mail) {
        if (!$mail instanceof MailContent) {
            continue;
        }
        /* @var $mail MailContent */
        $attachments = array();
        MailUtilities::parseMail($mail->getContent(), $decoded, $parsedEmail, $warnings);
        if (isset($parsedEmail['Attachments'])) {
            $attachments = $parsedEmail['Attachments'];
        } else {
            if ($mail->getHasAttachments() && !in_array($parsedEmail['Type'], array('html', 'text', 'delivery-status')) && isset($parsedEmail['FileName'])) {
                // if the email is the attachment
                $attachments = array(array('Data' => $parsedEmail['Data'], 'Type' => $parsedEmail['Type'], 'FileName' => $parsedEmail['FileName']));
            }
        }
        foreach ($attachments as $att) {
            $file = ProjectFiles::getByFilename($att['FileName']);
            /* @var $file ProjectFile */
            if ($file instanceof ProjectFile) {
                $file->setMailId($mail->getId());
                $file->setMarkTimestamps(false);
                // dont change updated_on date
                $file->save();
                $file->addToSharingTable();
            }
        }
    }
    DB::executeAll("UPDATE " . TABLE_PREFIX . "objects o INNER JOIN " . TABLE_PREFIX . "project_files f ON f.object_id=o.id\n\t\t\tSET o.updated_by_id=o.created_by_id, o.updated_on=o.created_on\n\t\t\tWHERE f.mail_id>0;");
}
 /**
  * Return parent file object
  *
  * @param void
  * @return ProjectFile
  */
 function getFile()
 {
     if (is_null($this->file)) {
         $this->file = ProjectFiles::findById($this->getFileId());
     }
     // if
     return $this->file;
 }
 /**
  * Return files
  *
  * @param void
  * @return array
  */
 function getFiles()
 {
     if (is_null($this->files)) {
         $this->files = ProjectFiles::getByFolder($this, logged_user()->isMemberOfOwnerCompany());
     }
     // if
     return $this->files;
 }
    /**
    * 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');
    }
Example #5
0
 /**
  * Clear all files and folders
  *
  * @param void
  * @return null
  */
 private function clearFiles()
 {
     $files = ProjectFiles::getAllFilesByProject($this);
     if (is_array($files)) {
         foreach ($files as $file) {
             $file->delete();
         }
         // foreach
     }
     // if
 }
 /**
  * Add comment
  *
  * Through this controller only logged users can post (no anonymous comments here)
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->setTemplate('add_comment');
     $object_id = get_id('object_id');
     $object = Objects::findObject($object_id);
     if (!$object instanceof ContentDataObject) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $comment = new Comment();
     $comment_data = array_var($_POST, 'comment');
     tpl_assign('comment_form_object', $object);
     tpl_assign('comment', $comment);
     tpl_assign('comment_data', $comment_data);
     if (is_array($comment_data)) {
         try {
             try {
                 $attached_files = ProjectFiles::handleHelperUploads(active_context());
             } catch (Exception $e) {
                 $attached_files = null;
             }
             // try
             $comment->setFromAttributes($comment_data);
             $comment->setRelObjectId($object_id);
             $comment->setObjectName(substr_utf($comment->getText(), 0, 250));
             DB::beginWork();
             $comment->save();
             $comment->addToMembers($object->getMembers());
             if (is_array($attached_files)) {
                 foreach ($attached_files as $attached_file) {
                     $comment->attachFile($attached_file);
                 }
                 // foreach
             }
             // if
             // Subscribe user to object
             if (!$object->isSubscriber(logged_user())) {
                 $object->subscribeUser(logged_user());
             }
             // if
             if (strlen($comment->getText()) < 100) {
                 $comment_head = $comment->getText();
             } else {
                 $lastpos = strpos($comment->getText(), " ", 100);
                 if ($lastpos === false) {
                     $comment_head = $comment->getText();
                 } else {
                     $comment_head = substr($comment->getText(), 0, $lastpos) . "...";
                 }
             }
             $comment_head = html_to_text($comment_head);
             ApplicationLogs::createLog($comment, ApplicationLogs::ACTION_COMMENT, false, false, true, $comment_head);
             DB::commit();
             flash_success(lang('success add comment'));
             ajx_current("reload");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }
    <ul class="listWithDetails">
<?php 
    if ($current_folder instanceof ProjectFolder) {
        ?>
      <li><a href="<?php 
        echo ProjectFiles::getIndexUrl($order, $page);
        ?>
"><?php 
        echo lang('all files');
        ?>
</a></li>
<?php 
    } else {
        ?>
      <li><a href="<?php 
        echo ProjectFiles::getIndexUrl($order, $page);
        ?>
" class="selected"><?php 
        echo lang('all files');
        ?>
</a></li>
<?php 
    }
    // if
    trace(__FILE__, 'folders');
    foreach ($folder_tree as $folder) {
        if ($current_folder instanceof ProjectFolder && $current_folder->getId() == $folder->getId()) {
            ?>
      <li><a href="<?php 
            echo $folder->getBrowseUrl($order);
            ?>
 /**
  * Add ticket
  *
  * @access public
  * @param void
  * @return null
  */
 function add_ticket()
 {
     $this->setTemplate('add_ticket');
     if (!ProjectTicket::canAdd(logged_user(), active_project())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('tickets'));
     }
     // if
     $ticket = new ProjectTicket();
     $ticket->setProjectId(active_project()->getId());
     $ticket_data = array_var($_POST, 'ticket');
     if (!is_array($ticket_data)) {
         $ticket_data = array('is_private' => config_option('default_private', false));
         // array
     }
     tpl_assign('ticket', $ticket);
     tpl_assign('ticket_data', $ticket_data);
     if (is_array(array_var($_POST, 'ticket'))) {
         try {
             $uploaded_files = ProjectFiles::handleHelperUploads(active_project());
         } catch (Exception $e) {
             $uploaded_files = null;
         }
         // try
         try {
             $ticket->setFromAttributes($ticket_data);
             $assigned_to = explode(':', array_var($ticket_data, 'assigned_to', ''));
             $ticket->setAssignedToCompanyId(array_var($assigned_to, 0, 0));
             $ticket->setAssignedToUserId(array_var($assigned_to, 1, 0));
             // Options are reserved only for members of owner company
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $ticket->setIsPrivate(false);
             }
             // if
             DB::beginWork();
             $ticket->save();
             if (is_array($uploaded_files)) {
                 foreach ($uploaded_files as $uploaded_file) {
                     $ticket->attachFile($uploaded_file);
                     $uploaded_file->setIsPrivate($ticket->isPrivate());
                     $uploaded_file->setIsVisible(true);
                     $uploaded_file->setExpirationTime(EMPTY_DATETIME);
                     $uploaded_file->save();
                 }
                 // if
             }
             // if
             ApplicationLogs::createLog($ticket, active_project(), ApplicationLogs::ACTION_ADD);
             DB::commit();
             // Try to send notifications but don't break submission in case of an error
             try {
                 if ($ticket->getAssignedToUserId()) {
                     $ticket_data['notify_user_' . $ticket->getAssignedToUserId()] = 'checked';
                 }
                 $notify_people = array();
                 $project_companies = active_project()->getCompanies();
                 foreach ($project_companies as $project_company) {
                     $company_users = $project_company->getUsersOnProject(active_project());
                     if (is_array($company_users)) {
                         foreach ($company_users as $company_user) {
                             if (array_var($ticket_data, 'notify_company_' . $project_company->getId()) == 'checked' || array_var($ticket_data, 'notify_user_' . $company_user->getId())) {
                                 $ticket->subscribeUser($company_user);
                                 // subscribe
                                 $notify_people[] = $company_user;
                             }
                             // if
                         }
                         // if
                     }
                     // if
                 }
                 // if
                 Notifier::ticket($ticket, $notify_people, 'new_ticket', $ticket->getCreatedBy());
             } catch (Exception $e) {
             }
             // try
             flash_success(lang('success add ticket', $ticket->getSummary()));
             $this->redirectTo('tickets');
             // Error...
         } catch (Exception $e) {
             DB::rollback();
             if (is_array($uploaded_files)) {
                 foreach ($uploaded_files as $uploaded_file) {
                     $uploaded_file->delete();
                 }
                 // foreach
             }
             // if
             $ticket->setNew(true);
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 /**
  * This function will return paginated result. Result is an array where first element is
  * array of returned object and second populated pagination object that can be used for
  * obtaining and rendering pagination data using various helpers.
  *
  * Items and pagination array vars are indexed with 0 for items and 1 for pagination
  * because you can't use associative indexing with list() construct
  *
  * @access public
  * @param array $arguments Query argumens (@see find()) Limit and offset are ignored!
  * @param integer $items_per_page Number of items per page
  * @param integer $current_page Current page number
  * @return array
  */
 function paginate($arguments = null, $items_per_page = 10, $current_page = 1)
 {
     if (isset($this) && instance_of($this, 'ProjectFiles')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return ProjectFiles::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 function reload_file_view()
 {
     ajx_current("reload");
     $file = ProjectFiles::findById(get_id());
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         return;
     }
     if (!$file->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         return;
     }
     if (array_var($_REQUEST, 'checkout')) {
         try {
             DB::beginWork();
             $file->checkOut();
             DB::commit();
             ApplicationLogs::createLog($file, ApplicationLogs::ACTION_CHECKOUT);
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
         }
     }
 }
 /**
  * Add comment
  * 
  * Through this controller only logged users can post (no anonymous comments here)
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->setTemplate('add_comment');
     $object_id = get_id('object_id');
     $object_manager = array_var($_GET, 'object_manager');
     if (!is_valid_function_name($object_manager)) {
         flash_error(lang('invalid request'));
         $this->redirectToUrl(active_project()->getOverviewUrl());
     }
     // if
     $object = get_object_by_manager_and_id($object_id, $object_manager);
     if (!$object instanceof ProjectDataObject || !$object->canComment(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToUrl(active_project()->getOverviewUrl());
     }
     // if
     $comment = new Comment();
     $comment_data = array_var($_POST, 'comment');
     tpl_assign('comment_form_object', $object);
     tpl_assign('comment', $comment);
     tpl_assign('comment_data', $comment_data);
     if (is_array($comment_data)) {
         try {
             try {
                 $attached_files = ProjectFiles::handleHelperUploads(active_project());
             } catch (Exception $e) {
                 $attached_files = null;
             }
             // try
             $comment->setFromAttributes($comment_data);
             $comment->setRelObjectId($object_id);
             $comment->setRelObjectManager($object_manager);
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $comment->setIsPrivate(false);
             }
             // if
             if ($object instanceof ProjectMessage || $object instanceof ProjectFile) {
                 if ($object->getIsPrivate()) {
                     $comment->setIsPrivate(true);
                 }
                 // if
             }
             // if
             DB::beginWork();
             $comment->save();
             if (is_array($attached_files)) {
                 foreach ($attached_files as $attached_file) {
                     $comment->attachFile($attached_file);
                 }
                 // foreach
             }
             // if
             ApplicationLogs::createLog($comment, active_project(), ApplicationLogs::ACTION_ADD);
             // Subscribe user to message (if $object is message)
             if ($object instanceof ProjectMessage) {
                 if (!$object->isSubscriber(logged_user())) {
                     $object->subscribeUser(logged_user());
                 }
                 // if
             }
             // if
             DB::commit();
             flash_success(lang('success add comment'));
             $redirect_to = $comment->getViewUrl();
             if (!is_valid_url($redirect_to)) {
                 $redirect_to = $object->getViewUrl();
             }
             // if
             $this->redirectToUrl($redirect_to);
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
Example #12
0
 function fileExists($username, $password, $filename)
 {
     $result = array('status' => true, 'errorid' => 0, 'message' => '');
     if ($this->loginUser($username, $password)) {
         $file = ProjectFiles::getByFilename($filename);
         $result['status'] = $file != null;
         if ($file != null) {
             $this->initXml('result');
             $this->instance->startElement('status');
             $this->instance->text('true');
             $this->instance->endElement();
             $this->instance->startElement('errorid');
             $this->instance->text(0);
             $this->instance->endElement();
             $this->instance->startElement('message');
             $this->file_toxml($file);
             $this->instance->endElement();
             $xml = $this->endXml();
         } else {
             $result['errorid'] = 1001;
             $result['message'] = lang('file dnx');
             $xml = $this->result_to_xml($result, 'result');
         }
     } else {
         $result['status'] = false;
         $result['errorid'] = 1002;
         $result['message'] = lang('invalid login data');
         $xml = $this->result_to_xml($result, 'result');
     }
     return $xml;
 }
 /**
  * Return paged project files
  *
  * @param Project $project
  * @param ProjectFolder $folder
  * @param boolean $hide_private Don't show private files
  * @param string $order Order files by name or by posttime (desc)
  * @param integer $page Current page
  * @param integer $files_per_page Number of files that will be showed per single page
  * @param boolean $group_by_order Group files by order field
  * @return array
  */
 static function getProjectFiles(Project $project, $folder = null, $hide_private = false, $order = null, $page = null, $files_per_page = null, $group_by_order = false)
 {
     trace(__FILE__, 'getProjectFiles()');
     if ($order == self::ORDER_BY_POSTTIME) {
         $order_by = '`created_on` DESC';
     } else {
         $order_by = '`filename`';
     }
     // if
     // #PAGE# is reserved as a placeholder
     //if (!($page == '#PAGE#')) {
     if ((int) $page < 1) {
         $page = 1;
     }
     if ((int) $files_per_page < 1) {
         $files_per_page = 10;
     }
     //} // if
     $folder_ids = array();
     if ($folder instanceof ProjectFolder && $folder->getProjectId() == $project->getId()) {
         if ($hide_private) {
             $conditions = array('`project_id` = ? AND `folder_id` = ? AND `is_private` = ? AND `is_visible` = ?', $project->getId(), $folder->getId(), false, true);
         } else {
             $conditions = array('`project_id` = ? AND `folder_id` = ? AND `is_visible` = ?', $project->getId(), $folder->getId(), true);
         }
         // if
     } else {
         if ($hide_private) {
             $conditions = array('`project_id` = ? AND `is_private` = ? AND `is_visible` = ?', $project->getId(), false, true);
         } else {
             $conditions = array('`project_id` = ? AND `is_visible` = ?', $project->getId(), true);
         }
         // if
     }
     // if
     list($files, $pagination) = ProjectFiles::paginate(array('conditions' => $conditions, 'order' => $order_by), $files_per_page, $page);
     if ($group_by_order) {
         $grouped_files = array();
         if (is_array($files) && count($files)) {
             $today = DateTimeValueLib::now();
             foreach ($files as $file) {
                 $group_by_str = '';
                 if ($order == self::ORDER_BY_POSTTIME) {
                     $created_on = $file->getCreatedOn();
                     if ($created_on->getYear() == $today->getYear()) {
                         $group_by_str = format_descriptive_date($created_on);
                     } else {
                         $group_by_str = format_date($created_on);
                     }
                     // if
                 } else {
                     $group_by_str = strtoupper(substr_utf($file->getFilename(), 0, 1));
                 }
                 // if
                 if (!isset($grouped_files[$group_by_str]) || !is_array($grouped_files[$group_by_str])) {
                     $grouped_files[$group_by_str] = array();
                 }
                 $grouped_files[$group_by_str][] = $file;
             }
             // foreach
         }
         // if
         $files = is_array($grouped_files) ? $grouped_files : null;
     }
     // if
     return array($files, $pagination);
 }
Example #14
0
/**
 * Call back function for file link
 * 
 * @param mixed $matches
 * @return
 */
function replace_file_link_callback($matches)
{
    if (count($matches) < 2) {
        return null;
    }
    // if
    if (!logged_user()->isMemberOfOwnerCompany()) {
        $object = ProjectFiles::findOne(array('conditions' => array('`id` = ? AND `project_id` = ? AND `is_private` = 0 ', $matches[1], active_project()->getId())));
    } else {
        $object = ProjectFiles::findOne(array('conditions' => array('`id` = ? AND `project_id` = ?', $matches[1], active_project()->getId())));
    }
    // if
    if (!$object instanceof ProjectFile) {
        return '<del>' . lang('invalid reference') . '</del>';
    } else {
        return '<a href="' . $object->getViewUrl() . '">' . $object->getFilename() . '</a>';
    }
    // if
}
Example #15
0
 /**
  * Clear all files and folders
  *
  * @param void
  * @return null
  */
 private function clearFiles()
 {
     $files = ProjectFiles::getAllFilesByProject($this);
     if (is_array($files)) {
         foreach ($files as $file) {
             if (count($file->getWorkspaces()) == 1) {
                 $file->delete();
             } else {
                 $file->removeFromWorkspace($this);
             }
             // if
         }
         // foreach
     }
     // if
 }
 /**
  * Function called from other controllers when creating a new object an linking objects to it
  *
  * @param void
  * @return null
  */
 function link_to_new_object($the_object)
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $objects = array_var($_POST, 'linked_objects');
     if (is_array($objects) && count($objects) > 0 && !$the_object->isNew() && !$the_object->canLinkObject(logged_user())) {
         flash_error(lang("user cannot link objects"));
         return;
     }
     $the_object->clearLinkedObjects();
     if (is_array($objects)) {
         $err = 0;
         foreach ($objects as $objid) {
             $split = explode(":", $objid);
             if ($split[0] == $the_object->getId()) {
                 continue;
             }
             if (count($split) == 1) {
                 $object = Objects::findObject($split[0]);
             } else {
                 if (count($split) == 3 && $split[2] == 'isName') {
                     $object = ProjectFiles::getByFilename($split[1]);
                 } else {
                     continue;
                 }
             }
             if ($object->canLinkObject(logged_user())) {
                 $the_object->linkObject($object);
                 if ($the_object instanceof ContentDataObject) {
                     ApplicationLogs::createLog($the_object, ApplicationLogs::ACTION_LINK, false, null, true, $object->getId());
                 }
                 if ($object instanceof ContentDataObject) {
                     ApplicationLogs::createLog($object, ApplicationLogs::ACTION_LINK, false, null, true, $the_object->getId());
                 }
             } else {
                 $err++;
             }
         }
         if ($err > 0) {
             flash_error(lang('some objects could not be linked', $err));
         }
     }
 }
Example #17
0
<?php

$panel = TabPanels::instance()->findById('documents-panel');
if ($panel instanceof TabPanel && $panel->getEnabled()) {
	$limit = 5 ;
	$result =  ProjectFiles::instance()->listing(array(
		"order" => "name",
		"order_dir" => "asc",
		"start" => 0,
		"limit" => $limit
	)) ;
	$active_members = array();
	$context = active_context();
	foreach ($context as $selection) {
		if ($selection instanceof Member) $active_members[] = $selection;
	}
	if (count($active_members) > 0) {
		$mnames = array();
		$allowed_contact_ids = array();
		foreach ($active_members as $member) {
			$mnames[] = clean($member->getName());
		}
		$widget_title = lang('documents'). ' '. lang('in').' '. implode(", ", $mnames);
	}
	
	$total = $result->total ;
	$documents = $result->objects;
	$genid = gen_id();
	if ($total) {
		include_once 'template.php';
	}
 static function canRead($bookId = null)
 {
     self::includeBasic();
     $file_id = self::ogBookId();
     if ($file_id == null) {
         return false;
     }
     if ($bookId != self::getGelsheetBookId($file_id)) {
         return false;
     }
     $file = ProjectFiles::findById($file_id);
     if (!$file instanceof ProjectFile) {
         return false;
     }
     return can_read(self::getCompanyWebsite()->getLoggedUser(), $file);
 }
 /**
  * Detach file from related object
  *
  * @param void
  * @return null
  */
 function detach_from_object()
 {
     $manager_class = array_var($_GET, 'manager');
     $object_id = get_id('object_id');
     $file_id = get_id('file_id');
     $object = get_object_by_manager_and_id($object_id, $manager_class);
     if (!$object instanceof ProjectDataObject) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $file = ProjectFiles::findById($file_id);
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $attached_file = AttachedFiles::findById(array('rel_object_manager' => $manager_class, 'rel_object_id' => $object_id, 'file_id' => $file_id));
     // findById
     if (!$attached_file instanceof AttachedFile) {
         flash_error(lang('file not attached to object'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     try {
         DB::beginWork();
         $attached_file->delete();
         DB::commit();
         flash_success(lang('success detach file'));
     } catch (Exception $e) {
         flash_error(lang('error detach file'));
         DB::rollback();
     }
     // try
     $this->redirectToReferer($object->getObjectUrl());
 }
Example #20
0
/**
 * Enter description here...
 * assumes manager has one field as PK
 *
 * @param DataManager $manager
 * @param $access_level ACCESS_LEVEL_XX objects that defines which permission is being checked
 * @param string $project_id string that will be compared to the project id while searching project_user table
 * @param int $user_id user whose permissions are being checked
 * @return unknown
 */
function permissions_sql_for_listings(DataManager $manager, $access_level, User $user, $project_id = '`project_id`', $table_alias = null)
{
    if (!$manager instanceof DataManager) {
        throw new Exception("Invalid manager '{$manager}' in permissions helper", -1);
        return '';
    }
    $user_id = $user->getId();
    $oup_tablename = ObjectUserPermissions::instance()->getTableName(true);
    $wo_tablename = WorkspaceObjects::instance()->getTableName(true);
    $users_table_name = Users::instance()->getTableName(true);
    $pu_table_name = ProjectUsers::instance()->getTableName(true);
    if ($user->isGuest() && $access_level == ACCESS_LEVEL_WRITE) {
        return 'false';
    }
    if (isset($table_alias) && $table_alias && $table_alias != '') {
        $object_table_name = $table_alias;
    } else {
        $object_table_name = $manager->getTableName();
    }
    if (!is_numeric($project_id)) {
        $project_id = "{$object_table_name}.{$project_id}";
    }
    $object_id_field = $manager->getPkColumns();
    $object_id = $object_table_name . '.' . $object_id_field;
    $object_manager = get_class($manager);
    $access_level_text = access_level_field_name($access_level);
    $item_class = $manager->getItemClass();
    $is_project_data_object = new $item_class() instanceof ProjectDataObject;
    // permissions for contacts
    if ($manager instanceof Contacts && can_manage_contacts($user)) {
        return 'true';
    }
    if ($manager instanceof Companies && can_manage_contacts($user)) {
        return 'true';
    }
    // permissions for file revisions
    if ($manager instanceof ProjectFileRevisions) {
        $pfTableName = "`" . TABLE_PREFIX . "project_files`";
        return "{$object_table_name}.`file_id` IN (SELECT `id` FROM {$pfTableName} WHERE " . permissions_sql_for_listings(ProjectFiles::instance(), $access_level, $user) . ")";
    }
    // permissions for projects
    if ($manager instanceof Projects) {
        $pcTableName = "`" . TABLE_PREFIX . 'project_users`';
        return "{$object_table_name}.`id` IN (SELECT `project_id` FROM {$pcTableName} `pc` WHERE `user_id` = {$user_id})";
    }
    // permissions for users
    if ($manager instanceof Users) {
        if (logged_user()->isMemberOfOwnerCompany()) {
            return "true";
        } else {
            return "{$object_table_name}.`company_id` = " . owner_company()->getId() . " OR {$object_table_name}.`company_id` = " . logged_user()->getCompanyId();
        }
    }
    $can_manage_object = manager_class_field_name($object_manager, $access_level);
    // user is creator
    $str = " ( `created_by_id` = {$user_id}) ";
    // element belongs to personal project
    /*if($is_project_data_object) // TODO: type of element belongs to a project
    			if (!in_array('project_id', $manager->getColumns())) {
    				$str .= "\n OR ( EXISTS(SELECT * FROM $users_table_name `xx_u`, $wo_tablename `xx_wo`
    				WHERE `xx_u`.`id` = $user_id
    					AND `xx_u`.`personal_project_id` = `xx_wo`.`workspace_id`
    					AND `xx_wo`.`object_id` = $object_id 
    					AND `xx_wo`.`object_manager` = '$object_manager' )) ";
    			} else {
    				$str .= "\n OR ( $project_id = (SELECT `personal_project_id` FROM $users_table_name `xx_u` WHERE `xx_u`.`id` = $user_id)) ";
    			}
    		*/
    // user or group has specific permissions over object
    $group_ids = $user->getGroupsCSV();
    $all_ids = '(' . $user_id . ($group_ids != '' ? ',' . $group_ids : '') . ')';
    $str .= "\n OR ( EXISTS ( SELECT * FROM {$oup_tablename} `xx_oup` \n\t\t\t\tWHERE `xx_oup`.`rel_object_id` = {$object_id} \n\t\t\t\t\tAND `xx_oup`.`rel_object_manager` = '{$object_manager}' \n\t\t\t\t\tAND `xx_oup`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_oup`.{$access_level_text} = true) )";
    if ($is_project_data_object) {
        // TODO: type of element belongs to a project
        if (!in_array('project_id', $manager->getColumns())) {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu`, {$wo_tablename} `xx_wo` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = `xx_wo`.`workspace_id`\n\t\t\t\t\tAND `xx_wo`.`object_id` = {$object_id} \n\t\t\t\t\tAND `xx_wo`.`object_manager` = '{$object_manager}'\n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        } else {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = {$project_id} \n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        }
    }
    // check account permissions in case of emails
    if ($manager instanceof MailContents) {
        $maccTableName = MailAccountUsers::instance()->getTableName(true);
        $str .= "\n OR EXISTS(SELECT `id` FROM {$maccTableName} WHERE `account_id` = {$object_table_name}.`account_id` AND `user_id` = {$user_id})";
        if (user_config_option('view deleted accounts emails', null, $user_id)) {
            $str .= "\n OR ((SELECT count(*) FROM `" . TABLE_PREFIX . "mail_accounts` WHERE `id` = {$object_table_name}.`account_id`) = 0) AND `created_by_id` = {$user_id}";
        }
    }
    $hookargs = array('manager' => $manager, 'access_level' => $access_level, 'user' => $user, 'project_id' => $project_id, 'table_alias' => $table_alias);
    Hook::fire('permissions_sql', $hookargs, $str);
    return ' (' . $str . ') ';
}
 /**
  * Add message
  *
  * @access public
  * @param void
  * @return null
  */
 function add()
 {
     $this->setTemplate('add_message');
     if (!ProjectMessage::canAdd(logged_user(), active_project())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('message'));
     }
     // if
     $message = new ProjectMessage();
     tpl_assign('message', $message);
     $message_data = array_var($_POST, 'message');
     if (!is_array($message_data)) {
         $message_data = array('milestone_id' => array_var($_GET, 'milestone_id'));
         // array
     }
     // if
     tpl_assign('message_data', $message_data);
     if (is_array(array_var($_POST, 'message'))) {
         try {
             $uploaded_files = ProjectFiles::handleHelperUploads(active_project());
         } catch (Exception $e) {
             $uploaded_files = null;
         }
         // try
         try {
             $message->setFromAttributes($message_data);
             $message->setProjectId(active_project()->getId());
             // Options are reserved only for members of owner company
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $message->setIsPrivate(false);
                 $message->setIsImportant(false);
                 $message->setCommentsEnabled(true);
                 $message->setAnonymousCommentsEnabled(false);
             }
             // if
             DB::beginWork();
             $message->save();
             $message->subscribeUser(logged_user());
             $message->setTagsFromCSV(array_var($message_data, 'tags'));
             if (is_array($uploaded_files)) {
                 foreach ($uploaded_files as $uploaded_file) {
                     $message->attachFile($uploaded_file);
                     $uploaded_file->setIsPrivate($message->isPrivate());
                     $uploaded_file->setIsVisible(true);
                     $uploaded_file->setExpirationTime(EMPTY_DATETIME);
                     $uploaded_file->save();
                 }
                 // if
             }
             // if
             ApplicationLogs::createLog($message, active_project(), ApplicationLogs::ACTION_ADD);
             DB::commit();
             // Try to send notifications but don't break submission in case of an error
             try {
                 $notify_people = array();
                 $project_companies = active_project()->getCompanies();
                 foreach ($project_companies as $project_company) {
                     $company_users = $project_company->getUsersOnProject(active_project());
                     if (is_array($company_users)) {
                         foreach ($company_users as $company_user) {
                             if (array_var($message_data, 'notify_company_' . $project_company->getId()) == 'checked' || array_var($message_data, 'notify_user_' . $company_user->getId())) {
                                 $message->subscribeUser($company_user);
                                 // subscribe
                                 $notify_people[] = $company_user;
                             }
                             // if
                         }
                         // if
                     }
                     // if
                 }
                 // if
                 Notifier::newMessage($message, $notify_people);
                 // send notification email...
             } catch (Exception $e) {
             }
             // try
             flash_success(lang('success add message', $message->getTitle()));
             $this->redirectTo('message');
             // Error...
         } catch (Exception $e) {
             DB::rollback();
             if (is_array($uploaded_files)) {
                 foreach ($uploaded_files as $uploaded_file) {
                     $uploaded_file->delete();
                 }
                 // foreach
             }
             // if
             $message->setNew(true);
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 function classifyFile($classification_data, $email, $parsedEmail, $validWS, $mantainWs = true, $csv = '')
 {
     if (!is_array($classification_data)) {
         $classification_data = array();
     }
     if (!isset($parsedEmail["Attachments"])) {
         throw new Exception(lang('no attachments found for email'));
     }
     for ($c = 0; $c < count($classification_data); $c++) {
         if (isset($classification_data["att_" . $c]) && $classification_data["att_" . $c]) {
             $att = $parsedEmail["Attachments"][$c];
             $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]);
             if (trim($fName) == "" && strlen($att["FileName"]) > 0) {
                 $fName = utf8_encode($att["FileName"]);
             }
             try {
                 $file = ProjectFiles::findOne(array('conditions' => "`filename` = " . DB::escape($fName) . " AND `mail_id` = " . $email->getId()));
                 DB::beginWork();
                 if ($file == null) {
                     $fileIsNew = true;
                     $file = new ProjectFile();
                     $file->setFilename($fName);
                     $file->setIsVisible(true);
                     $file->setIsPrivate(false);
                     $file->setIsImportant(false);
                     $file->setCommentsEnabled(true);
                     $file->setAnonymousCommentsEnabled(false);
                     $file->setMailId($email->getId());
                     $file->save();
                 } else {
                     $fileIsNew = false;
                 }
                 if (!$mantainWs && !$fileIsNew) {
                     $file->removeFromWorkspaces(logged_user()->getWorkspacesQuery());
                 }
                 foreach ($validWS as $w) {
                     if (!$file->hasWorkspace($w)) {
                         $file->addToWorkspace($w);
                     }
                 }
                 $file->setTagsFromCSV($csv);
                 $enc = array_var($parsedMail, 'Encoding', 'UTF-8');
                 $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc);
                 $mime_type = '';
                 if (Mime_Types::instance()->has_type($att["content-type"])) {
                     $mime_type = $att["content-type"];
                     //mime type is listed & valid
                 } else {
                     $mime_type = Mime_Types::instance()->get_type($ext);
                     //Attempt to infer mime type
                 }
                 if ($fileIsNew) {
                     $tempFileName = ROOT . "/tmp/" . logged_user()->getId() . "x" . gen_id();
                     $fh = fopen($tempFileName, 'w') or die("Can't open file");
                     fwrite($fh, $att["Data"]);
                     fclose($fh);
                     $fileToSave = array("name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName));
                     $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject()));
                     // handle uploaded file
                     $email->linkObject($file);
                     ApplicationLogs::createLog($file, $email->getWorkspaces(), ApplicationLogs::ACTION_ADD);
                 }
                 DB::commit();
                 // Error...
             } catch (Exception $e) {
                 DB::rollback();
                 flash_error($e->getMessage());
                 ajx_current("empty");
             }
             if (isset($tempFileName) && is_file($tempFileName)) {
                 unlink($tempFileName);
             }
         }
     }
 }
 /**
  * Return file
  *
  * @param void
  * @return ProjectFile
  */
 function getFile()
 {
     return ProjectFiles::findById($this->getFileId());
 }
 function fckimagesbrowser()
 {
     /* get query parameters */
     $this->setLayout('html');
     ajx_current("empty");
     $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');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $project = active_project();
     $tag = array_var($_GET, 'tag');
     $type = '%image/';
     $paginatedImages = ProjectFiles::getProjectFiles($project, null, $hide_private, $order, $orderdir, $page, $limit, false, $tag, $type, logged_user()->getId());
     tpl_assign('start', $start);
     tpl_assign('limit', $limit);
     tpl_assign('paginatedImages', $paginatedImages);
 }
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return ProjectFiles 
  */
 function manager()
 {
     if (!$this->manager instanceof ProjectFiles) {
         $this->manager = ProjectFiles::instance();
     }
     return $this->manager;
 }
Example #26
0
 /**
 * Clear all files and folders
 *
 * @param void
 * @return null
 */
 private function clearFiles() {
   if(!plugin_active('files')) { return null; }
   $files = ProjectFiles::getAllFilesByProject($this);
   if (is_array($files)) {
     foreach ($files as $file) {
       $file->delete();
     } // foreach
   } // if
 } // clearFiles
Example #27
0
 /**
 * Return array of active projects that this user have access
 *
 * @access public
 * @param void
 * @return array
 */
 function getImportantFiles($sort = 'name') {
   trace(__FILE__, 'getImportantFiles()');
   if (is_null($this->importantfiles)) {
     trace(__FILE__, '- initialize cache: files');
     $this->importantfiles = array();
   } // if
   if (!isset($this->importantfiles[$sort])) {
     $files = array();
     $projects = $this->getActiveProjects();
     if (is_array($projects)) {
       foreach($projects as $project) {
         $projectfiles = ProjectFiles::getImportantProjectFiles($project);
         $i=0;
         while (isset($projectfiles[$i])){
           $files[] = $projectfiles[$i];
           unset($projectfiles[$i]);
           $i++;
         }
       }
     }
     usort($files, "filenamecmp");
     $this->importantfiles[$sort] = $files;
   } // if
   return $this->importantfiles[$sort];
 } // getImportantFiles
 function uploadDocument($doc_name, $ws_id, $path)
 {
     if (str_starts_with($doc_name, "~")) {
         return;
     }
     try {
         DB::beginWork();
         $project = Projects::findById($ws_id);
         //$file = ProjectFiles::findOne(array("conditions" => "`filename` = '$doc_name'"));
         $files = ProjectFiles::getAllByFilename($doc_name, $ws_id);
         if (is_array($files) && count($files) > 0) {
             $file = $files[0];
         } else {
             $file = null;
         }
         if (!$file instanceof ProjectFile) {
             $file = new ProjectFile();
             $file->setFilename($doc_name);
             $file->setIsVisible(true);
             $file->setIsPrivate(false);
             $file->setIsImportant(false);
             $file->setCommentsEnabled(true);
             $file->setAnonymousCommentsEnabled(false);
             //$file->setCreatedOn(new DateTimeValue(time()) );
         }
         $sourcePath = $path . $doc_name;
         $handle = fopen($sourcePath, "r");
         $size = filesize($sourcePath);
         $file_content = fread($handle, $size);
         fclose($handle);
         $file_dt['name'] = $file->getFilename();
         $file_dt['size'] = strlen($file_content);
         $file_dt['tmp_name'] = $sourcePath;
         //TEMP_PATH . DIRECTORY_SEPARATOR . rand() ;
         $extension = trim(get_file_extension($sourcePath));
         $file_dt['type'] = Mime_Types::instance()->get_type($extension);
         if (!trim($file_dt['type'])) {
             $file_dt['type'] = 'text/html';
         }
         $file->save();
         $file->removeFromAllWorkspaces();
         $file->addToWorkspace($project);
         $old_revs = $file->getRevisions();
         foreach ($old_revs as $rev) {
             $rev->delete();
         }
         $revision = $file->handleUploadedFile($file_dt, true, '');
         $file_date = new DateTimeValue(filemtime($sourcePath));
         $revision->setCreatedOn($file_date);
         $revision->setUpdatedOn($file_date);
         $revision->save();
         $file->setCreatedOn($file_date);
         $file->setUpdatedOn($file_date);
         $file->save();
         $ws = $file->getWorkspaces();
         ApplicationLogs::createLog($file, $ws, ApplicationLogs::ACTION_ADD);
         ImportLogger::instance()->log("   File: {$doc_name} [{$ws_id}]");
         print "   File: {$doc_name} [{$ws_id}]\r\n";
         DB::commit();
     } catch (Exception $e) {
         DB::rollback();
         ImportLogger::instance()->logError("{$e}\r\n**************************************************");
         print "\r\n\r\nERROR: {$e}\r\n";
     }
 }
 /**
  * Empty implementation of abstract methods. Messages determine does user have
  * permissions to add comment
  *
  * @param void
  * @return null
  */
 function canAdd(User $user, Project $project)
 {
     return can_add($user, $project, get_class(ProjectFiles::instance()));
 }
	function display_content() {
		
		$file = ProjectFiles::findById(get_id());
		if (!$file instanceof ProjectFile) {
			die(lang("file dnx"));
		}
		if (!$file->canView(logged_user())) {
			die(lang("no access permissions"));
		}
		
		if (defined('SANDBOX_URL')) {
			$html_content = $file->getFileContentWithRealUrls();
		} else {
			$html_content = purify_html($file->getFileContentWithRealUrls());
		}
		$charset = "";
		if ($file->getTypeString() == "text/html") {
			$encoding = detect_encoding($html_content, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'));
			$charset = ";charset=".$encoding;
		}
		
		if ($file->getTypeString() == 'text/html') {
			// Include stylesheet from FCK Editor
			$css = '<style type="text/css">';
			$css .= file_get_contents(ROOT.'/public/assets/javascript/ckeditor/contents.css');
			$css .= '</style>';
			$html_content = $css.$html_content;
		}
		
		header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Content-Type: " . $file->getTypeString() . $charset);
		header("Content-Length: " . (string) strlen($html_content));

		print($html_content);
		die();
	}