Exemplo n.º 1
0
 /**
  * Run dashboard.
  */
 public function run()
 {
     // Add dashboard js and css
     $resources = CRM_Core_Resources::singleton();
     $resources->addScriptFile('civicrm', 'js/jquery/jquery.dashboard.js', 0, 'html-header', FALSE);
     $resources->addStyleFile('civicrm', 'css/dashboard.css');
     $this->assign('contactDashlets', CRM_Core_BAO_Dashboard::getContactDashletsForJS());
     CRM_Utils_System::setTitle(ts('CiviCRM Home'));
     $contactID = CRM_Core_Session::getLoggedInContactID();
     // call hook to get html from other modules
     // ignored but needed to prevent warnings
     $contentPlacement = CRM_Utils_Hook::DASHBOARD_BELOW;
     $html = CRM_Utils_Hook::dashboard($contactID, $contentPlacement);
     if (is_array($html)) {
         $this->assign_by_ref('hookContent', $html);
         $this->assign('hookContentPlacement', $contentPlacement);
     }
     $communityMessages = CRM_Core_CommunityMessages::create();
     if ($communityMessages->isEnabled()) {
         $message = $communityMessages->pick();
         if ($message) {
             $this->assign('communityMessages', $communityMessages->evalMarkup($message['markup']));
         }
     }
     return parent::run();
 }
Exemplo n.º 2
0
 /**
  * Checks whether the logged in user has permission to perform an action
  * against a specified project.
  *
  * @param int $op
  *   See the constants in CRM_Core_Action.
  * @param int $projectId
  *   Required for some but not all operations.
  * @return boolean
  *   TRUE is the action is allowed; else FALSE.
  */
 public static function checkProjectPerms($op, $projectId = NULL)
 {
     $opsRequiringProjectId = array(CRM_Core_Action::UPDATE, CRM_Core_Action::DELETE);
     if (in_array($op, $opsRequiringProjectId) && empty($projectId)) {
         CRM_Core_Error::fatal('Missing required parameter Project ID');
     }
     $contactId = CRM_Core_Session::getLoggedInContactID();
     switch ($op) {
         case CRM_Core_Action::ADD:
             return self::check('create volunteer projects');
         case CRM_Core_Action::UPDATE:
             if (self::check('edit all volunteer projects')) {
                 return TRUE;
             }
             $projectOwners = CRM_Volunteer_BAO_Project::getContactsByRelationship($projectId, 'volunteer_owner');
             if (self::check('edit own volunteer projects') && in_array($contactId, $projectOwners)) {
                 return TRUE;
             }
             break;
         case CRM_Core_Action::DELETE:
             if (self::check('delete all volunteer projects')) {
                 return TRUE;
             }
             $projectOwners = CRM_Volunteer_BAO_Project::getContactsByRelationship($projectId, 'volunteer_owner');
             if (self::check('delete own volunteer projects') && in_array($contactId, $projectOwners)) {
                 return TRUE;
             }
             break;
         case CRM_Core_Action::VIEW:
             if (self::check('register to volunteer') || self::check('edit all volunteer projects')) {
                 return TRUE;
             }
     }
     return FALSE;
 }
Exemplo n.º 3
0
 /**
  * Takes an associative array and creates an instance object.
  *
  * the function extract all the params it needs to initialize the create a
  * instance object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Report_DAO_ReportInstance
  */
 public static function add(&$params)
 {
     $instance = new CRM_Report_DAO_ReportInstance();
     if (empty($params)) {
         return NULL;
     }
     $instanceID = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('instance_id', $params));
     // convert roles array to string
     if (isset($params['grouprole']) && is_array($params['grouprole'])) {
         $grouprole_array = array();
         foreach ($params['grouprole'] as $key => $value) {
             $grouprole_array[$value] = $value;
         }
         $params['grouprole'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($grouprole_array));
     }
     if (!$instanceID || !isset($params['id'])) {
         $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
         $params['domain_id'] = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
         // CRM-17256 set created_id on report creation.
         $params['created_id'] = isset($params['created_id']) ? $params['created_id'] : CRM_Core_Session::getLoggedInContactID();
     }
     if ($instanceID) {
         CRM_Utils_Hook::pre('edit', 'ReportInstance', $instanceID, $params);
     } else {
         CRM_Utils_Hook::pre('create', 'ReportInstance', NULL, $params);
     }
     $instance = new CRM_Report_DAO_ReportInstance();
     $instance->copyValues($params);
     if (CRM_Core_Config::singleton()->userFramework == 'Joomla') {
         $instance->permission = 'null';
     }
     // explicitly set to null if params value is empty
     if (!$instanceID && empty($params['grouprole'])) {
         $instance->grouprole = 'null';
     }
     if ($instanceID) {
         $instance->id = $instanceID;
     }
     if (!$instanceID) {
         if ($reportID = CRM_Utils_Array::value('report_id', $params)) {
             $instance->report_id = $reportID;
         } elseif ($instanceID) {
             $instance->report_id = CRM_Report_Utils_Report::getValueFromUrl($instanceID);
         } else {
             // just take it from current url
             $instance->report_id = CRM_Report_Utils_Report::getValueFromUrl();
         }
     }
     $instance->save();
     if ($instanceID) {
         CRM_Utils_Hook::pre('edit', 'ReportInstance', $instance->id, $instance);
     } else {
         CRM_Utils_Hook::pre('create', 'ReportInstance', $instance->id, $instance);
     }
     return $instance;
 }
Exemplo n.º 4
0
 /**
  * This virtual function is used to set the default values of
  * various form elements
  *
  * access        public
  *
  * @return array
  *   reference to the array of default values
  */
 public function setDefaultValues()
 {
     // CRM-11761 retrieve user's activity filter preferences
     $defaults = array();
     $userID = CRM_Core_Session::getLoggedInContactID();
     if ($userID) {
         $defaults = Civi::service('settings_manager')->getBagByContact(NULL, $userID)->get('activity_tab_filter');
     }
     return $defaults;
 }
 public static function checkFilePerms($op, $file, $user)
 {
     $opsRequiringProjectId = array(CRM_Core_Action::UPDATE, CRM_Core_Action::DELETE);
     if (in_array($op, $opsRequiringProjectId) && empty($projectId)) {
         CRM_Core_Error::fatal('Missing required parameter Project ID');
     }
     //Run the hook that allows third party extensions to
     //Alter the permissions of a file operation.
     //If true, they have permission
     //If False, they expressly do not
     //If null, fallback on the following checks.
     $validByHook = CRM_Securefiles_Hooks::checkPermissions($op, $file, $user);
     if (!is_null($validByHook)) {
         return $validByHook;
     }
     $contactId = CRM_Core_Session::getLoggedInContactID();
     $checkUserRelationship = !($contactId == $user);
     switch ($op) {
         case CRM_Core_Action::ADD:
         case CRM_Core_Action::UPDATE:
             if ($checkUserRelationship) {
                 return self::check('upload others secure files');
                 //Todo: Check relationships and allow for permissioned relationships
             } else {
                 return self::check('upload own secure files');
             }
             break;
         case CRM_Core_Action::DELETE:
             if ($checkUserRelationship) {
                 return self::check("delete all secure files");
                 //Todo: Check relationships and allow for permissioned relationships
             } else {
                 return self::check("delete own secure files");
             }
             break;
         case CRM_Core_Action::VIEW:
             if ($checkUserRelationship) {
                 return self::check('view all secure files');
                 //Todo: Check relationships and allow for permissioned relationships
             } else {
                 return self::check('view own secure files');
             }
             break;
         case self::LIST_SECURE_FILES:
             if ($checkUserRelationship) {
                 return self::check('list all secure files');
                 //Todo: Check relationships and allow for permissioned relationships
             } else {
                 return self::check('list own secure files');
             }
             break;
     }
     return FALSE;
 }
Exemplo n.º 6
0
 static function registerScripts()
 {
     static $loaded = FALSE;
     if ($loaded) {
         return;
     }
     $loaded = TRUE;
     CRM_Core_Resources::singleton()->addSettingsFactory(function () {
         global $user;
         $settings = array();
         $config = CRM_Core_Config::singleton();
         $extensions = CRM_Core_PseudoConstant::getExtensions();
         return array('Appraisals' => array('extensionPath' => CRM_Core_Resources::singleton()->getUrl('uk.co.compucorp.civicrm.appraisals'), 'settings' => $settings, 'permissions' => array()), 'adminId' => CRM_Core_Session::getLoggedInContactID(), 'contactId' => CRM_Utils_Request::retrieve('cid', 'Integer'), 'debug' => $config->debug);
     });
 }
Exemplo n.º 7
0
 /**
  * @param array $pages
  * @param string $fileName
  * @param array|int $format
  */
 public static function html2doc($pages, $fileName, $format = array())
 {
     if (is_array($format)) {
         // PDF Page Format parameters passed in - merge with defaults
         $format += CRM_Core_BAO_PdfFormat::getDefaultValues();
     } else {
         // PDF Page Format ID passed in
         $format = CRM_Core_BAO_PdfFormat::getById($format);
     }
     $paperSize = CRM_Core_BAO_PaperSize::getByName($format['paper_size']);
     $metric = CRM_Core_BAO_PdfFormat::getValue('metric', $format);
     $pageStyle = array('orientation' => CRM_Core_BAO_PdfFormat::getValue('orientation', $format), 'pageSizeW' => self::toTwip($paperSize['width'], $paperSize['metric']), 'pageSizeH' => self::toTwip($paperSize['height'], $paperSize['metric']), 'marginTop' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_top', $format), $metric), 'marginRight' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_right', $format), $metric), 'marginBottom' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_bottom', $format), $metric), 'marginLeft' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_left', $format), $metric));
     $ext = pathinfo($fileName, PATHINFO_EXTENSION);
     $phpWord = new \PhpOffice\PhpWord\PhpWord();
     $phpWord->getDocInfo()->setCreator(CRM_Core_DAO::getFieldValue('CRM_Contact_BAO_Contact', CRM_Core_Session::getLoggedInContactID(), 'display_name'));
     foreach ((array) $pages as $page => $html) {
         $section = $phpWord->addSection($pageStyle + array('breakType' => 'nextPage'));
         \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html);
     }
     self::printDoc($phpWord, $ext, $fileName);
 }
Exemplo n.º 8
0
 function run($args = NULL)
 {
     if (CRM_Utils_Array::value(0, $args) !== 'civicrm' || CRM_Utils_Array::value(1, $args) !== 'volunteer') {
         CRM_Core_Error::fatal('Invalid page callback config.');
         return;
     }
     switch (CRM_Utils_Array::value(2, $args)) {
         /**
          * This routes civicrm/volunteer/join to CiviVolunteer's reserved profile for volunteer interest.
          */
         case 'join':
             // the profile expects the ID (and some other parameters) to be passed via URL; since we are providing
             // a nice clean URL, these parameters won't be there, so we fake it
             $_REQUEST['gid'] = civicrm_api3('UFGroup', 'getvalue', array('sequential' => 1, 'name' => "volunteer_interest", 'return' => "id"));
             $_REQUEST['force'] = '1';
             // if the user is logged in, serve edit mode profile; else serve create mode
             $contact_id = CRM_Core_Session::getLoggedInContactID();
             // set params for controller
             $class = 'CRM_Profile_Form_Edit';
             $title = NULL;
             $mode = isset($contact_id) ? CRM_Core_Action::UPDATE : CRM_Core_Action::ADD;
             $imageUpload = FALSE;
             $addSequence = FALSE;
             $ignoreKey = TRUE;
             $attachUpload = FALSE;
             $controller = new CRM_Core_Controller_Simple($class, $title, $mode, $imageUpload, $addSequence, $ignoreKey, $attachUpload);
             if (isset($contact_id)) {
                 $controller->set('edit', 1);
             }
             $controller->process();
             return $controller->run();
         default:
             CRM_Core_Error::fatal('Invalid page callback config.');
             return;
     }
 }
Exemplo n.º 9
0
 /**
  * Create the event.
  *
  * @param array $params
  *   Reference array contains the values submitted by the form.
  *
  * @return object
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     if (empty($params['is_template'])) {
         $params['is_template'] = 0;
     }
     // check if new event, if so set the created_id (if not set)
     // and always set created_date to now
     if (empty($params['id'])) {
         if (empty($params['created_id'])) {
             $session = CRM_Core_Session::singleton();
             $params['created_id'] = $session->get('userID');
         }
         $params['created_date'] = date('YmdHis');
     }
     $event = self::add($params);
     CRM_Price_BAO_PriceSet::setPriceSets($params, $event, 'event');
     if (is_a($event, 'CRM_Core_Error')) {
         CRM_Core_DAO::transaction('ROLLBACK');
         return $event;
     }
     $contactId = CRM_Core_Session::getLoggedInContactID();
     if (!$contactId) {
         $contactId = CRM_Utils_Array::value('contact_id', $params);
     }
     // Log the information on successful add/edit of Event
     $logParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id, 'modified_id' => $contactId, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_event', $event->id);
     }
     $transaction->commit();
     return $event;
 }
Exemplo n.º 10
0
 /**
  * Save changes made by user to the Dashlet.
  *
  * @param array $columns
  *
  * @param int $contactID
  *
  * @throws RuntimeException
  */
 public static function saveDashletChanges($columns, $contactID = NULL)
 {
     if (!$contactID) {
         $contactID = CRM_Core_Session::getLoggedInContactID();
     }
     if (empty($contactID)) {
         throw new RuntimeException("Failed to determine contact ID");
     }
     $dashletIDs = array();
     if (is_array($columns)) {
         foreach ($columns as $colNo => $dashlets) {
             if (!is_int($colNo)) {
                 continue;
             }
             $weight = 1;
             foreach ($dashlets as $dashletID => $isMinimized) {
                 $dashletID = (int) $dashletID;
                 $query = "INSERT INTO civicrm_dashboard_contact\n                    (weight, column_no, is_active, dashboard_id, contact_id)\n                    VALUES({$weight}, {$colNo}, 1, {$dashletID}, {$contactID})\n                    ON DUPLICATE KEY UPDATE weight = {$weight}, column_no = {$colNo}, is_active = 1";
                 // fire update query for each column
                 CRM_Core_DAO::executeQuery($query);
                 $dashletIDs[] = $dashletID;
                 $weight++;
             }
         }
     }
     // Disable inactive widgets
     $dashletClause = $dashletIDs ? "dashboard_id NOT IN  (" . implode(',', $dashletIDs) . ")" : '(1)';
     $updateQuery = "UPDATE civicrm_dashboard_contact\n                    SET is_active = 0\n                    WHERE {$dashletClause} AND contact_id = {$contactID}";
     CRM_Core_DAO::executeQuery($updateQuery);
 }
Exemplo n.º 11
0
 /**
  * Get all the groups the user has access to for the given operation.
  *
  * @param int $type
  *   The type of permission needed.
  * @param int $contactID
  *   The contactID for whom the check is made.
  *
  * @param string $tableName
  * @param null $allGroups
  * @param null $includedGroups
  *
  * @return array
  *   the ids of the groups for which the user has permissions
  */
 public static function group($type, $contactID = NULL, $tableName = 'civicrm_saved_search', $allGroups = NULL, $includedGroups = NULL)
 {
     if ($contactID == NULL) {
         $contactID = CRM_Core_Session::getLoggedInContactID();
     }
     if (!$contactID) {
         // anonymous user
         $contactID = 0;
     }
     return CRM_ACL_BAO_ACL::group($type, $contactID, $tableName, $allGroups, $includedGroups);
 }
/**
 * Helper function to get the default project relationships for a new project.
 *
 * @return array
 */
function _volunteerGetProjectRelationshipDefaults()
{
    $defaults = array();
    $relTypes = CRM_Core_OptionGroup::values("volunteer_project_relationship", true, FALSE, FALSE, NULL, 'name');
    $ownerType = $relTypes['volunteer_owner'];
    $managerType = $relTypes['volunteer_manager'];
    $beneficiaryType = $relTypes['volunteer_beneficiary'];
    $contactId = CRM_Core_Session::getLoggedInContactID();
    $defaults[$ownerType] = array($contactId);
    $defaults[$managerType] = array($contactId);
    $employerRelationshipTypeId = civicrm_api3('RelationshipType', 'getvalue', array('return' => "id", 'name_b_a' => "Employer of"));
    try {
        $result = civicrm_api3('Relationship', 'getvalue', array('return' => "contact_id_b", 'contact_id_a' => $contactId, 'relationship_type_id' => $employerRelationshipTypeId, 'is_active' => 1));
        $defaultBeneficiary = array($result);
    } catch (Exception $e) {
        $domain = civicrm_api3('Domain', 'getsingle', array('current_domain' => 1));
        $defaultBeneficiary = array($domain['contact_id']);
    }
    $defaults[$beneficiaryType] = $defaultBeneficiary;
    return $defaults;
}
Exemplo n.º 13
0
 /**
  * @inheritDoc
  */
 public function addSelectWhereClause()
 {
     // We always return an array with these keys, even if they are empty,
     // because this tells the query builder that we have considered these fields for acls
     $clauses = array('id' => array(), 'is_deleted' => CRM_Core_Permission::check('administer CiviCase') ? array() : array("= 0"));
     // Ensure the user has permission to view the case client
     $contactClause = CRM_Utils_SQL::mergeSubquery('Contact');
     if ($contactClause) {
         $contactClause = implode(' AND contact_id ', $contactClause);
         $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id {$contactClause})";
     }
     // The api gatekeeper ensures the user has at least "access my cases and activities"
     // so if they do not have permission to see all cases we'll assume they can only access their own
     if (!CRM_Core_Permission::check('access all cases and activities')) {
         $user = (int) CRM_Core_Session::getLoggedInContactID();
         $clauses['id'][] = "IN (\n        SELECT r.case_id FROM civicrm_relationship r, civicrm_case_contact cc WHERE r.is_active = 1 AND cc.case_id = r.case_id AND (\n          (r.contact_id_a = cc.contact_id AND r.contact_id_b = {$user}) OR (r.contact_id_b = cc.contact_id AND r.contact_id_a = {$user})\n        )\n      )";
     }
     CRM_Utils_Hook::selectWhereClause($this, $clauses);
     return $clauses;
 }
Exemplo n.º 14
0
 /**
  * Post process function.
  *
  * @param CRM_Core_Form $form
  * @param bool $redirect
  */
 public static function postProcess(&$form, $redirect = TRUE)
 {
     $params = $form->getVar('_params');
     $instanceID = $form->getVar('_id');
     if ($isNew = $form->getVar('_createNew')) {
         // set the report_id since base template is going to be same, and we going to unset $instanceID
         // which will make it difficult later on, to compute report_id
         $params['report_id'] = CRM_Report_Utils_Report::getValueFromUrl($instanceID);
         // Unset $instanceID so a new copy would be created.
         $instanceID = NULL;
     }
     $params['instance_id'] = $instanceID;
     if (!empty($params['is_navigation'])) {
         $params['navigation'] = $form->_navigation;
     } elseif ($instanceID) {
         // Delete navigation if exists.
         $navId = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'navigation_id', 'id');
         if ($navId) {
             CRM_Core_BAO_Navigation::processDelete($navId);
             CRM_Core_BAO_Navigation::resetNavigation();
         }
     }
     // make a copy of params
     $formValues = $params;
     // unset params from $formValues that doesn't match with DB columns of instance tables, and also not required in form-values for sure
     $unsetFields = array('title', 'to_emails', 'cc_emails', 'header', 'footer', 'qfKey', 'id', '_qf_default', 'report_header', 'report_footer', 'grouprole', 'task');
     foreach ($unsetFields as $field) {
         unset($formValues[$field]);
     }
     $view_mode = $formValues['view_mode'];
     // CRM-17310 my reports functionality - we should set owner if the checkbox is 1,
     // it seems to be not set at all if unchecked.
     if (!empty($formValues['add_to_my_reports'])) {
         $params['owner_id'] = CRM_Core_Session::getLoggedInContactID();
     } else {
         $params['owner_id'] = 'null';
     }
     unset($formValues['add_to_my_reports']);
     // pass form_values as string
     $params['form_values'] = serialize($formValues);
     $instance = CRM_Report_BAO_ReportInstance::create($params);
     $form->set('id', $instance->id);
     if ($instanceID && !$isNew) {
         // updating existing instance
         $statusMsg = ts('"%1" report has been updated.', array(1 => $instance->title));
     } elseif ($form->getVar('_id') && $isNew) {
         $statusMsg = ts('Your report has been successfully copied as "%1". You are currently viewing the new copy.', array(1 => $instance->title));
     } else {
         $statusMsg = ts('"%1" report has been successfully created. You are currently viewing the new report instance.', array(1 => $instance->title));
     }
     CRM_Core_Session::setStatus($statusMsg);
     if ($redirect) {
         $urlParams = array('reset' => 1);
         if ($view_mode == 'view') {
             $urlParams['force'] = 1;
         } else {
             $urlParams['output'] = 'criteria';
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/report/instance/{$instance->id}", $urlParams));
     }
 }
Exemplo n.º 15
0
 /**
  * @todo Is there a better way to do this?
  * @return string
  */
 private function getPrimaryEmail()
 {
     $uid = CRM_Core_Session::getLoggedInContactID();
     $primary = '';
     $emails = CRM_Core_BAO_Email::allEmails($uid);
     foreach ($emails as $eid => $e) {
         if ($e['is_primary']) {
             if ($e['email']) {
                 $primary = $e['email'];
                 break;
             }
         }
         if (count($emails) == 1) {
             $primary = $e['email'];
             break;
         }
     }
     return $primary;
 }
Exemplo n.º 16
0
 /**
  * React to a financial transaction (payment) failure.
  *
  * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
  * payments is important for forensic and outreach reasons.
  *
  * @param int $contributionID
  * @param string $message
  */
 public static function failPayment($contributionID, $contactID, $message)
 {
     civicrm_api3('activity', 'create', array('activity_type_id' => 'Failed Payment', 'details' => $message, 'subject' => ts('Payment failed at payment processor'), 'source_record_id' => $contributionID, 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : $contactID));
 }
Exemplo n.º 17
0
/**
 * Mailing submit.
 *
 * @param array $params
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_mailing_submit($params)
{
    civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
    if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
        throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
    }
    if (!is_numeric(CRM_Core_Session::getLoggedInContactID())) {
        throw new API_Exception("Failed to determine current user");
    }
    $updateParams = array();
    $updateParams['id'] = $params['id'];
    // Note: we'll pass along scheduling/approval fields, but they may get ignored
    // if we don't have permission.
    if (isset($params['scheduled_date'])) {
        $updateParams['scheduled_date'] = $params['scheduled_date'];
        $updateParams['scheduled_id'] = CRM_Core_Session::getLoggedInContactID();
    }
    if (isset($params['approval_date'])) {
        $updateParams['approval_date'] = $params['approval_date'];
        $updateParams['approver_id'] = CRM_Core_Session::getLoggedInContactID();
        $updateParams['approval_status_id'] = CRM_Utils_Array::value('approval_status_id', $updateParams, CRM_Core_OptionGroup::getDefaultValue('mail_approval_status'));
    }
    if (isset($params['approval_note'])) {
        $updateParams['approval_note'] = $params['approval_note'];
    }
    if (isset($params['_skip_evil_bao_auto_recipients_'])) {
        $updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
    }
    $updateParams['options']['reload'] = 1;
    return civicrm_api3('Mailing', 'create', $updateParams);
}
Exemplo n.º 18
0
 /**
  * Construct a WHERE clause to handle permissions to $object_*
  *
  * @param array $tables
  *   Any tables that may be needed in the FROM.
  * @param string $operation
  *   The operation being attempted.
  * @param string $object_table
  *   The table of the object in question.
  * @param int $object_id
  *   The ID of the object in question.
  * @param int $acl_id
  *   If it's a grant/revoke operation, the ACL ID.
  * @param bool $acl_role
  *   For grant operations, this flag determines if we're granting a single acl (false) or an entire group.
  *
  * @return string
  *   The WHERE clause, or 0 on failure
  */
 public static function permissionClause(&$tables, $operation, $object_table = NULL, $object_id = NULL, $acl_id = NULL, $acl_role = FALSE)
 {
     $dao = new CRM_ACL_DAO_ACL();
     $t = array('ACL' => self::getTableName(), 'ACLRole' => 'civicrm_acl_role', 'ACLEntityRole' => CRM_ACL_DAO_EntityRole::getTableName(), 'Contact' => CRM_Contact_DAO_Contact::getTableName(), 'Group' => CRM_Contact_DAO_Group::getTableName(), 'GroupContact' => CRM_Contact_DAO_GroupContact::getTableName());
     $contact_id = CRM_Core_Session::getLoggedInContactID();
     $where = " {$t['ACL']}.operation = '" . CRM_Utils_Type::escape($operation, 'String') . "'";
     /* Include clause if we're looking for a specific table/id permission */
     if (!empty($object_table)) {
         $where .= " AND ( {$t['ACL']}.object_table IS null\n                         OR ({$t['ACL']}.object_table   = '" . CRM_Utils_Type::escape($object_table, 'String') . "'";
         if (!empty($object_id)) {
             $where .= " AND ({$t['ACL']}.object_id IS null\n                            OR {$t['ACL']}.object_id = " . CRM_Utils_Type::escape($object_id, 'Integer') . ')';
         }
         $where .= '))';
     }
     /* Include clause if we're granting an ACL or ACL Role */
     if (!empty($acl_id)) {
         $where .= " AND ({$t['ACL']}.acl_id IS null\n                        OR {$t['ACL']}.acl_id   = " . CRM_Utils_Type::escape($acl_id, 'Integer') . ')';
         if ($acl_role) {
             $where .= " AND {$t['ACL']}.acl_table = '{$t['ACLRole']}'";
         } else {
             $where .= " AND {$t['ACL']}.acl_table = '{$t['ACL']}'";
         }
     }
     $query = array();
     /* Query for permissions granted to all contacts in the domain */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    WHERE       {$t['ACL']}.entity_table    = '{$t['Domain']}'\n                            AND ({$where})";
     /* Query for permissions granted to all contacts through an ACL group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON      {$t['ACL']}.entity_id =\n                                    {$t['ACLRole']}.id\n\n                    WHERE       {$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Domain']}'\n                            AND {$t['ACLRole']}.is_active      = 1\n                            AND ({$where})";
     /* Query for permissions granted directly to the contact */
     $query[] = "SELECT      {$t['ACL']}.*, 1 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['Contact']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['Contact']}'\n                            AND     {$t['ACL']}.entity_id = {$t['Contact']}.id)\n\n                    WHERE       {$t['Contact']}.id          = {$contact_id}\n                            AND ({$where})";
     /* Query for permissions granted to the contact through an ACL group */
     $query[] = "SELECT      {$t['ACL']}.*, 1 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id\n\n                    WHERE       {$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Contact']}'\n                        AND     {$t['ACLRole']}.is_active      = 1\n                        AND     {$t['ACLEntityRole']}.entity_id  = {$contact_id}\n                        AND     ({$where})";
     /* Query for permissions granted to the contact through a group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['GroupContact']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['Group']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['GroupContact']}.group_id)\n\n                    WHERE       ({$where})\n                        AND     {$t['GroupContact']}.contact_id = {$contact_id}\n                        AND     {$t['GroupContact']}.status     = 'Added')";
     /* Query for permissions granted through an ACL group to a Contact
      * group */
     $query[] = "SELECT      {$t['ACL']}.*, 0 as override\n                    FROM        {$t['ACL']}\n\n                    INNER JOIN  {$t['ACLEntityRole']}\n                            ON  ({$t['ACL']}.entity_table = '{$t['ACLRole']}'\n                            AND     {$t['ACL']}.entity_id =\n                                    {$t['ACLEntityRole']}.acl_role_id)\n\n                    INNER JOIN  {$t['ACLRole']}\n                            ON  {$t['ACL']}.entity_id = {$t['ACLRole']}.id\n\n                    INNER JOIN  {$t['GroupContact']}\n                            ON  ({$t['ACLEntityRole']}.entity_table =\n                                    '{$t['Group']}'\n                            AND     {$t['ACLEntityRole']}.entity_id =\n                                    {$t['GroupContact']}.group_id)\n\n                    WHERE       ({$where})\n                        AND     {$t['ACLRole']}.is_active      = 1\n                        AND     {$t['GroupContact']}.contact_id = {$contact_id}\n                        AND     {$t['GroupContact']}.status     = 'Added'";
     $union = '(' . implode(') UNION DISTINCT (', $query) . ')';
     $dao->query($union);
     $allow = array(0);
     $deny = array(0);
     $override = array();
     while ($dao->fetch()) {
         /* Instant bypass for the following cases:
          * 1) the rule governs all tables
          * 2) the rule governs all objects in the table in question
          * 3) the rule governs the specific object we want
          */
         if (empty($dao->object_table) || $dao->object_table == $object_table && (empty($dao->object_id) || $dao->object_id == $object_id)) {
             $clause = 1;
         } else {
             /* Otherwise try to generate a clause for this rule */
             $clause = self::getClause($dao->object_table, $dao->object_id, $tables);
             /* If the clause returned is null, then the rule is a blanket
              * (id is null) on a table other than the one we're interested
              * in.  So skip it. */
             if (empty($clause)) {
                 continue;
             }
         }
         /* Now we figure out if this is an allow or deny rule, and possibly
          * a contact-level override */
         if ($dao->deny) {
             $deny[] = $clause;
         } else {
             $allow[] = $clause;
             if ($dao->override) {
                 $override[] = $clause;
             }
         }
     }
     $allows = '(' . implode(' OR ', $allow) . ')';
     $denies = '(' . implode(' OR ', $deny) . ')';
     if (!empty($override)) {
         $denies = '(NOT (' . implode(' OR ', $override) . ") AND {$denies})";
     }
     return "({$allows} AND NOT {$denies})";
 }
Exemplo n.º 19
0
 /**
  * Get the cache key string for the merge action.
  *
  * @param int $rule_group_id
  * @param int $group_id
  * @param array $criteria
  *   Additional criteria to narrow down the merge group.
  *   Currently we are only supporting the key 'contact' within it.
  *
  * @param bool $checkPermissions
  *   Respect the users permissions.
  *
  * @return string
  */
 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE)
 {
     $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
     $cacheKeyString = "merge {$contactType}";
     $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
     $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
     $cacheKeyString .= !empty($criteria) ? serialize($criteria) : '_0';
     if ($checkPermissions) {
         $contactID = CRM_Core_Session::getLoggedInContactID();
         if (!$contactID) {
             // Distinguish between no permission check & no logged in user.
             $contactID = 'null';
         }
         $cacheKeyString .= '_' . $contactID;
     } else {
         $cacheKeyString .= '_0';
     }
     return $cacheKeyString;
 }
/**
 * Helper function to get the default project relationships for a new project.
 *
 * @return array
 */
function _volunteerGetProjectRelationshipDefaults()
{
    $defaults = array();
    $relTypes = CRM_Core_OptionGroup::values("volunteer_project_relationship", true, FALSE, FALSE, NULL, 'name');
    $ownerType = $relTypes['volunteer_owner'];
    $managerType = $relTypes['volunteer_manager'];
    $beneficiaryType = $relTypes['volunteer_beneficiary'];
    $contactId = CRM_Core_Session::getLoggedInContactID();
    $defaults[$ownerType] = array('contact_id' => $contactId);
    $defaults[$managerType] = array('contact_id' => $contactId);
    $employerRelationshipTypeId = civicrm_api3('RelationshipType', 'getvalue', array('return' => "id", 'name_b_a' => "Employer of"));
    try {
        $result = civicrm_api3('Relationship', 'getvalue', array('return' => "contact_id_b", 'contact_id_a' => $contactId, 'relationship_type_id' => $employerRelationshipTypeId, 'is_active' => 1));
        $defaultBeneficiary = array('contact_id' => $result);
    } catch (Exception $e) {
        $domain = civicrm_api3('Domain', 'getsingle', array('current_domain' => 1));
        $defaultBeneficiary = array('contact_id' => $domain['contact_id']);
    }
    $defaults[$beneficiaryType] = $defaultBeneficiary;
    //Re-Format the defaults into the expected structure
    //each type should be an array of arrays, each one
    //containing two keys, one for contact_id, and one for read permissions
    //$defaults['type'] => array( array('contact_id' => ..., 'can_be_read_by_current_user' => ...) )git
    foreach ($defaults as $type => &$contacts) {
        foreach ($contacts as &$contact) {
            if (!is_array($contact)) {
                $contact = array("contact_id" => $contact);
            }
            $contact['can_be_read_by_current_user'] = CRM_Volunteer_BAO_ProjectContact::contactIsReadable($contact['contact_id']);
        }
    }
    return $defaults;
}
Exemplo n.º 21
0
 /**
  * Run this page (figure out the action needed and perform it).
  *
  * @param int $id
  * @param int $contactID
  * @param bool $print
  * @param bool $allowID
  *
  * @return null|string
  *   Not really sure if anything should be returned - parent doesn't
  */
 public function run($id = NULL, $contactID = NULL, $print = TRUE, $allowID = FALSE)
 {
     if (is_numeric($id)) {
         $this->_mailingID = $id;
     } else {
         $print = TRUE;
         $this->_mailingID = CRM_Utils_Request::retrieve('id', 'String', CRM_Core_DAO::$_nullObject, TRUE);
     }
     // # CRM-7651
     // override contactID from the function level if passed in
     if (isset($contactID) && is_numeric($contactID)) {
         $this->_contactID = $contactID;
     } else {
         $this->_contactID = CRM_Core_Session::getLoggedInContactID();
     }
     // mailing key check
     if (Civi::settings()->get('hash_mailing_url')) {
         $this->_mailing = new CRM_Mailing_BAO_Mailing();
         if (!is_numeric($this->_mailingID)) {
             $this->_mailing->hash = $this->_mailingID;
         } elseif (is_numeric($this->_mailingID)) {
             $this->_mailing->id = $this->_mailingID;
             // if mailing is present and associated hash is present
             // while 'hash' is not been used for mailing view : throw 'permissionDenied'
             if ($this->_mailing->find() && CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $this->_mailingID, 'hash', 'id') && !$allowID) {
                 CRM_Utils_System::permissionDenied();
                 return NULL;
             }
         }
     } else {
         $this->_mailing = new CRM_Mailing_BAO_Mailing();
         $this->_mailing->id = $this->_mailingID;
     }
     if (!$this->_mailing->find(TRUE) || !$this->checkPermission()) {
         CRM_Utils_System::permissionDenied();
         return NULL;
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($this->_mailing);
     // get and format attachments
     $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $this->_mailing->id);
     // get contact detail and compose if contact id exists
     $returnProperties = $this->_mailing->getReturnProperties();
     if (isset($this->_contactID)) {
         // get details of contact with token value including Custom Field Token Values.CRM-3734
         $params = array('contact_id' => $this->_contactID);
         $details = CRM_Utils_Token::getTokenDetails($params, $returnProperties, FALSE, TRUE, NULL, $this->_mailing->getFlattenedTokens(), get_class($this));
         $details = $details[0][$this->_contactID];
         $contactId = $this->_contactID;
     } else {
         // get tokens that are not contact specific resolved
         $params = array('contact_id' => 0);
         $details = CRM_Utils_Token::getAnonymousTokenDetails($params, $returnProperties, TRUE, TRUE, NULL, $this->_mailing->getFlattenedTokens(), get_class($this));
         $details = CRM_Utils_Array::value(0, $details[0]);
         $contactId = 0;
     }
     $mime = $this->_mailing->compose(NULL, NULL, NULL, $contactId, $this->_mailing->from_email, $this->_mailing->from_email, TRUE, $details, $attachments);
     $title = NULL;
     if (isset($this->_mailing->body_html) && empty($_GET['text'])) {
         $header = 'text/html; charset=utf-8';
         $content = $mime->getHTMLBody();
         if (strpos($content, '<head>') === FALSE && strpos($content, '<title>') === FALSE) {
             $title = '<head><title>' . $this->_mailing->subject . '</title></head>';
         }
     } else {
         $header = 'text/plain; charset=utf-8';
         $content = $mime->getTXTBody();
     }
     CRM_Utils_System::setTitle($this->_mailing->subject);
     if (CRM_Utils_Array::value('snippet', $_GET) === 'json') {
         CRM_Core_Page_AJAX::returnJsonResponse($content);
     }
     if ($print) {
         CRM_Utils_System::setHttpHeader('Content-Type', $header);
         print $title;
         print $content;
         CRM_Utils_System::civiExit();
     } else {
         return $content;
     }
 }
Exemplo n.º 22
0
 /**
  * Build the form object.
  */
 public function preProcess()
 {
     CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
     $this->_atypefile = CRM_Utils_Array::value('atypefile', $_GET);
     $this->assign('atypefile', FALSE);
     if ($this->_atypefile) {
         $this->assign('atypefile', TRUE);
     }
     $session = CRM_Core_Session::singleton();
     $this->_currentUserId = CRM_Core_Session::getLoggedInContactID();
     $this->_currentlyViewedContactId = $this->get('contactId');
     if (!$this->_currentlyViewedContactId) {
         $this->_currentlyViewedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     }
     $this->assign('contactId', $this->_currentlyViewedContactId);
     // Give the context.
     if (!isset($this->_context)) {
         $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
         if (CRM_Contact_Form_Search::isSearchContext($this->_context)) {
             $this->_context = 'search';
         } elseif (!in_array($this->_context, array('dashlet', 'dashletFullscreen')) && $this->_currentlyViewedContactId) {
             $this->_context = 'activity';
         }
         $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
     }
     $this->assign('context', $this->_context);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (!CRM_Core_Permission::check('delete activities')) {
             CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
         }
     }
     // CRM-6957
     // When we come from contact search, activity id never comes.
     // So don't try to get from object, it might gives you wrong one.
     // if we're not adding new one, there must be an id to
     // an activity we're trying to work on.
     if ($this->_action != CRM_Core_Action::ADD && get_class($this->controller) != 'CRM_Contact_Controller_Search') {
         $this->_activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     }
     $this->_activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
     $this->assign('atype', $this->_activityTypeId);
     $this->assign('activityId', $this->_activityId);
     // Check for required permissions, CRM-6264.
     if ($this->_activityId && in_array($this->_action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW)) && !CRM_Activity_BAO_Activity::checkPermission($this->_activityId, $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     if ($this->_action & CRM_Core_Action::VIEW && CRM_Activity_BAO_Activity::checkPermission($this->_activityId, CRM_Core_Action::UPDATE)) {
         $this->assign('permission', 'edit');
     }
     if (!$this->_activityTypeId && $this->_activityId) {
         $this->_activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId, 'activity_type_id');
     }
     // Assigning Activity type name.
     if ($this->_activityTypeId) {
         $activityTName = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId, 'label');
         if ($activityTName[$this->_activityTypeId]) {
             $this->_activityTypeName = $activityTName[$this->_activityTypeId];
             $this->assign('activityTName', $activityTName[$this->_activityTypeId]);
         }
     }
     // Set title.
     if (isset($activityTName)) {
         $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
         $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
         if ($this->_currentlyViewedContactId) {
             $displayName = CRM_Contact_BAO_Contact::displayName($this->_currentlyViewedContactId);
             // Check if this is default domain contact CRM-10482.
             if (CRM_Contact_BAO_Contact::checkDomainContact($this->_currentlyViewedContactId)) {
                 $displayName .= ' (' . ts('default organization') . ')';
             }
             CRM_Utils_System::setTitle($displayName . ' - ' . $activityName);
         } else {
             CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
         }
     }
     // Check the mode when this form is called either single or as
     // search task action.
     if ($this->_activityTypeId || $this->_context == 'standalone' || $this->_currentlyViewedContactId) {
         $this->_single = TRUE;
         $this->assign('urlPath', 'civicrm/activity');
     } else {
         // Set the appropriate action.
         $url = CRM_Utils_System::currentPath();
         $urlArray = explode('/', $url);
         $searchPath = array_pop($urlArray);
         $searchType = 'basic';
         $this->_action = CRM_Core_Action::BASIC;
         switch ($searchPath) {
             case 'basic':
                 $searchType = $searchPath;
                 $this->_action = CRM_Core_Action::BASIC;
                 break;
             case 'advanced':
                 $searchType = $searchPath;
                 $this->_action = CRM_Core_Action::ADVANCED;
                 break;
             case 'builder':
                 $searchType = $searchPath;
                 $this->_action = CRM_Core_Action::PROFILE;
                 break;
             case 'custom':
                 $this->_action = CRM_Core_Action::COPY;
                 $searchType = $searchPath;
                 break;
         }
         parent::preProcess();
         $this->_single = FALSE;
         $this->assign('urlPath', "civicrm/contact/search/{$searchType}");
         $this->assign('urlPathVar', "_qf_Activity_display=true&qfKey={$this->controller->_key}");
     }
     $this->assign('single', $this->_single);
     $this->assign('action', $this->_action);
     if ($this->_action & CRM_Core_Action::VIEW) {
         // Get the tree of custom fields.
         $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Activity', $this, $this->_activityId, 0, $this->_activityTypeId);
     }
     if ($this->_activityTypeId) {
         // Set activity type name and description to template.
         list($this->_activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($this->_activityTypeId);
         $this->assign('activityTypeName', $this->_activityTypeName);
         $this->assign('activityTypeDescription', $activityTypeDescription);
     }
     // set user context
     $urlParams = $urlString = NULL;
     $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
     if (!$qfKey) {
         $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
     }
     // Validate the qfKey.
     if (!CRM_Utils_Rule::qfKey($qfKey)) {
         $qfKey = NULL;
     }
     if ($this->_context == 'fulltext') {
         $keyName = '&qfKey';
         $urlParams = 'force=1';
         $urlString = 'civicrm/contact/search/custom';
         if ($this->_action == CRM_Core_Action::UPDATE) {
             $keyName = '&key';
             $urlParams .= '&context=fulltext&action=view';
             $urlString = 'civicrm/contact/view/activity';
         }
         if ($qfKey) {
             $urlParams .= "{$keyName}={$qfKey}";
         }
         $this->assign('searchKey', $qfKey);
     } elseif (in_array($this->_context, array('standalone', 'home', 'dashlet', 'dashletFullscreen'))) {
         $urlParams = 'reset=1';
         $urlString = 'civicrm/dashboard';
     } elseif ($this->_context == 'search') {
         $urlParams = 'force=1';
         if ($qfKey) {
             $urlParams .= "&qfKey={$qfKey}";
         }
         $path = CRM_Utils_System::currentPath();
         if ($this->_compContext == 'advanced') {
             $urlString = 'civicrm/contact/search/advanced';
         } elseif ($path == 'civicrm/group/search' || $path == 'civicrm/contact/search' || $path == 'civicrm/contact/search/advanced' || $path == 'civicrm/contact/search/custom' || $path == 'civicrm/group/search') {
             $urlString = $path;
         } else {
             $urlString = 'civicrm/activity/search';
         }
         $this->assign('searchKey', $qfKey);
     } elseif ($this->_context != 'caseActivity') {
         $urlParams = "action=browse&reset=1&cid={$this->_currentlyViewedContactId}&selectedChild=activity";
         $urlString = 'civicrm/contact/view';
     }
     if ($urlString) {
         $session->pushUserContext(CRM_Utils_System::url($urlString, $urlParams));
     }
     // hack to retrieve activity type id from post variables
     if (!$this->_activityTypeId) {
         $this->_activityTypeId = CRM_Utils_Array::value('activity_type_id', $_POST);
     }
     // when custom data is included in this page
     if (!empty($_POST['hidden_custom'])) {
         // We need to set it in the session for the code below to work.
         // CRM-3014
         // Need to assign custom data subtype to the template.
         $this->set('type', 'Activity');
         $this->set('subType', $this->_activityTypeId);
         $this->set('entityId', $this->_activityId);
         CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeId, 1, 'Activity', $this->_activityId);
         CRM_Custom_Form_CustomData::buildQuickForm($this);
         CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     // add attachments part
     CRM_Core_BAO_File::buildAttachment($this, 'civicrm_activity', $this->_activityId, NULL, TRUE);
     // figure out the file name for activity type, if any
     if ($this->_activityTypeId && ($this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir))) {
         $this->assign('activityTypeFile', $this->_activityTypeFile);
         $this->assign('crmDir', $this->_crmDir);
     }
     $this->setFields();
     if ($this->_activityTypeFile) {
         $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
         $className::preProcess($this);
     }
     $this->_values = $this->get('values');
     if (!is_array($this->_values)) {
         $this->_values = array();
         if (isset($this->_activityId) && $this->_activityId) {
             $params = array('id' => $this->_activityId);
             CRM_Activity_BAO_Activity::retrieve($params, $this->_values);
         }
         $this->set('values', $this->_values);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
     }
 }
Exemplo n.º 23
0
/**
 * Determine a contact ID using a string expression.
 *
 * @param string $contactIdExpr
 *   E.g. "user_contact_id" or "@user:username".
 *
 * @return int|NULL|'unknown-user'
 */
function _civicrm_api3_resolve_contactID($contactIdExpr)
{
    // If value = 'user_contact_id' replace value with logged in user id.
    if ($contactIdExpr == "user_contact_id") {
        return CRM_Core_Session::getLoggedInContactID();
    } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
        $config = CRM_Core_Config::singleton();
        $ufID = $config->userSystem->getUfId($matches[1]);
        if (!$ufID) {
            return 'unknown-user';
        }
        $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
        if (!$contactID) {
            return 'unknown-user';
        }
        return $contactID;
    }
    return NULL;
}
Exemplo n.º 24
0
 /**
  * Create a follow up a given activity.
  *
  * @param int $activityId
  *   activity id of parent activity.
  * @param array $params
  *
  * @return CRM_Activity_BAO_Activity|null|object
  */
 public static function createFollowupActivity($activityId, $params)
 {
     if (!$activityId) {
         return NULL;
     }
     $followupParams = array();
     $followupParams['parent_id'] = $activityId;
     $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
     $followupParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
     $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
     // Get Subject of Follow-up Activiity, CRM-4491
     $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
     $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
     // Create target contact for followup.
     if (!empty($params['target_contact_id'])) {
         $followupParams['target_contact_id'] = $params['target_contact_id'];
     }
     $followupParams['activity_date_time'] = CRM_Utils_Date::processDate($params['followup_date'], $params['followup_date_time']);
     $followupActivity = self::create($followupParams);
     return $followupActivity;
 }
Exemplo n.º 25
0
 /**
  * Combine all the exportable fields from the lower levels object.
  *
  * Currently we are using importable fields as exportable fields
  *
  * @param int|string $contactType contact Type
  * @param bool $status
  *   True while exporting primary contacts.
  * @param bool $export
  *   True when used during export.
  * @param bool $search
  *   True when used during search, might conflict with export param?.
  *
  * @param bool $withMultiRecord
  *
  * @return array
  *   array of exportable Fields
  */
 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE)
 {
     if (empty($contactType)) {
         $contactType = 'All';
     }
     $cacheKeyString = "exportableFields {$contactType}";
     $cacheKeyString .= $export ? '_1' : '_0';
     $cacheKeyString .= $status ? '_1' : '_0';
     $cacheKeyString .= $search ? '_1' : '_0';
     //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
     //calculates custom fields takes into account the logged in user & caches that for all users
     //as an interim fix we will cache the fields by contact
     $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
     if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
         if (!self::$_exportableFields) {
             self::$_exportableFields = array();
         }
         // check if we can retrieve from database cache
         $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
         if (!$fields) {
             $fields = CRM_Contact_DAO_Contact::export();
             // The fields are meant for contact types.
             if (in_array($contactType, array('Individual', 'Household', 'Organization', 'All'))) {
                 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
             }
             // add current employer for individuals
             $fields = array_merge($fields, array('current_employer' => array('name' => 'organization_name', 'title' => ts('Current Employer'))));
             $locationType = array('location_type' => array('name' => 'location_type', 'where' => 'civicrm_location_type.name', 'title' => ts('Location Type')));
             $IMProvider = array('im_provider' => array('name' => 'im_provider', 'where' => 'civicrm_im.provider_id', 'title' => ts('IM Provider')));
             $locationFields = array_merge($locationType, CRM_Core_DAO_Address::export(), CRM_Core_DAO_Phone::export(), CRM_Core_DAO_Email::export(), $IMProvider, CRM_Core_DAO_IM::export(TRUE), CRM_Core_DAO_OpenID::export());
             $locationFields = array_merge($locationFields, CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
             foreach ($locationFields as $key => $field) {
                 $locationFields[$key]['hasLocationType'] = TRUE;
             }
             $fields = array_merge($fields, $locationFields);
             //add world region
             $fields = array_merge($fields, CRM_Core_DAO_Worldregion::export());
             $fields = array_merge($fields, CRM_Contact_DAO_Contact::export());
             //website fields
             $fields = array_merge($fields, CRM_Core_DAO_Website::export());
             if ($contactType != 'All') {
                 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord));
             } else {
                 foreach (array('Individual', 'Household', 'Organization') as $type) {
                     $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord));
                 }
             }
             //fix for CRM-791
             if ($export) {
                 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'), 'name' => 'groups'), 'tags' => array('title' => ts('Tag(s)'), 'name' => 'tags'), 'notes' => array('title' => ts('Note(s)'), 'name' => 'notes')));
             } else {
                 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'), 'name' => 'group'), 'tag' => array('title' => ts('Tag(s)'), 'name' => 'tag'), 'note' => array('title' => ts('Note(s)'), 'name' => 'note')));
             }
             //Sorting fields in alphabetical order(CRM-1507)
             foreach ($fields as $k => $v) {
                 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
             }
             $fields = array_merge($sortArray, $fields);
             //unset the field which are not related to their contact type.
             if ($contactType != 'All') {
                 $commonValues = array('Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom'), 'Household' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'organization_name', 'legal_name', 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased', 'deceased_date', 'current_employer', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'prefix_id', 'suffix_id'), 'Organization' => array('first_name', 'middle_name', 'last_name', 'formal_title', 'job_title', 'gender_id', 'prefix_id', 'suffix_id', 'birth_date', 'household_name', 'email_greeting_custom', 'postal_greeting_custom', 'prefix_id', 'suffix_id', 'gender_id', 'addressee_custom', 'is_deceased', 'deceased_date', 'current_employer'));
                 foreach ($commonValues[$contactType] as $value) {
                     unset($fields[$value]);
                 }
             }
             CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
         }
         self::$_exportableFields[$cacheKeyString] = $fields;
     }
     if (!$status) {
         $fields = self::$_exportableFields[$cacheKeyString];
     } else {
         $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))), self::$_exportableFields[$cacheKeyString]);
     }
     return $fields;
 }
Exemplo n.º 26
0
Arquivo: API.php Projeto: kidaa30/yes
 /**
  * Get the permissioned where clause for the user.
  *
  * @param int $type
  *   The type of permission needed.
  * @param array $tables
  *   (reference ) add the tables that are needed for the select clause.
  * @param array $whereTables
  *   (reference ) add the tables that are needed for the where clause.
  * @param int $contactID
  *   The contactID for whom the check is made.
  * @param bool $onlyDeleted
  *   Whether to include only deleted contacts.
  * @param bool $skipDeleteClause
  *   Don't add delete clause if this is true,.
  *   this means it is handled by generating query
  *
  * @return string
  *   the group where clause for this user
  */
 public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL, $onlyDeleted = FALSE, $skipDeleteClause = FALSE)
 {
     // the default value which is valid for the final AND
     $deleteClause = ' ( 1 ) ';
     if (!$skipDeleteClause) {
         if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
             $deleteClause = '(contact_a.is_deleted)';
         } else {
             // CRM-6181
             $deleteClause = '(contact_a.is_deleted = 0)';
         }
     }
     // first see if the contact has edit / view all contacts
     if (CRM_Core_Permission::check('edit all contacts') || $type == self::VIEW && CRM_Core_Permission::check('view all contacts')) {
         return $deleteClause;
     }
     if (!$contactID) {
         $contactID = CRM_Core_Session::getLoggedInContactID();
     }
     $contactID = (int) $contactID;
     $where = implode(' AND ', array(CRM_ACL_BAO_ACL::whereClause($type, $tables, $whereTables, $contactID), $deleteClause));
     // Add permission on self
     if ($contactID && (CRM_Core_Permission::check('edit my contact') || $type == self::VIEW && CRM_Core_Permission::check('view my contact'))) {
         $where = "(contact_a.id = {$contactID} OR ({$where}))";
     }
     return $where;
 }
Exemplo n.º 27
0
 /**
  * Get the permissioned where clause for the user.
  *
  * @param int $type
  *   The type of permission needed.
  * @param array $tables
  *   (reference ) add the tables that are needed for the select clause.
  * @param array $whereTables
  *   (reference ) add the tables that are needed for the where clause.
  * @param int $contactID
  *   The contactID for whom the check is made.
  * @param bool $onlyDeleted
  *   Whether to include only deleted contacts.
  * @param bool $skipDeleteClause
  *   Don't add delete clause if this is true,.
  *   this means it is handled by generating query
  *
  * @return string
  *   the group where clause for this user
  */
 public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL, $onlyDeleted = FALSE, $skipDeleteClause = FALSE)
 {
     // the default value which is valid for the final AND
     $deleteClause = ' ( 1 ) ';
     if (!$skipDeleteClause) {
         if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
             $deleteClause = '(contact_a.is_deleted)';
         } else {
             // CRM-6181
             $deleteClause = '(contact_a.is_deleted = 0)';
         }
     }
     // first see if the contact has edit / view all contacts
     if (CRM_Core_Permission::check('edit all contacts') || $type == self::VIEW && CRM_Core_Permission::check('view all contacts')) {
         return $deleteClause;
     }
     $user = CRM_Core_Session::getLoggedInContactID();
     if ($contactID == NULL) {
         $contactID = $user ? $user : 0;
     }
     // Check if contact has permissions on self
     if ($user && $contactID == $user) {
         if (CRM_Core_Permission::check('edit my contact') || $type == self::VIEW && CRM_Core_Permission::check('view my contact')) {
             return ' ( 1 ) ';
         }
     }
     return implode(' AND ', array(CRM_ACL_BAO_ACL::whereClause($type, $tables, $whereTables, $contactID), $deleteClause));
 }
/**
 * Returns array of projects matching a set of one or more project properties
 *
 * @param array $params  Array of one or more valid
 *                       property_name=>value pairs. If $params is set
 *                       as null, all projects will be returned
 *
 * @return array  Array of matching projects
 * {@getfields volunteer_project_get}
 * @access public
 */
function civicrm_api3_volunteer_project_get($params)
{
    //If we are in an editing context only show projects they can edit.
    $context = CRM_Utils_Array::value('context', $params);
    if ($context === 'edit' && !CRM_Volunteer_Permission::check('edit all volunteer projects')) {
        if (!isset($params['project_contacts'])) {
            $params['project_contacts'] = array();
        }
        $params['project_contacts']['volunteer_owner'] = array(CRM_Core_Session::getLoggedInContactID());
        unset($params['context']);
    }
    $result = CRM_Volunteer_BAO_Project::retrieve($params);
    foreach ($result as $k => $bao) {
        $result[$k] = $bao->toArray();
        $result[$k]['entity_attributes'] = $bao->getEntityAttributes();
        $profiles = civicrm_api3("UFJoin", "get", array("entity_id" => $bao->id, "entity_table" => "civicrm_volunteer_project", "options" => array("limit" => 0), "sequential" => 1));
        $result[$k]['profiles'] = $profiles['values'];
    }
    return civicrm_api3_create_success($result, $params, 'VolunteerProject', 'get');
}
Exemplo n.º 29
0
 /**
  * Generate acl subquery that can be placed in the WHERE clause of a query or the ON clause of a JOIN
  *
  * @return string|null
  */
 public static function cacheSubquery()
 {
     if (!CRM_Core_Permission::check(array(array('view all contacts', 'edit all contacts')))) {
         $contactID = (int) CRM_Core_Session::getLoggedInContactID();
         self::cache($contactID);
         return "IN (SELECT contact_id FROM civicrm_acl_contact_cache WHERE user_id = {$contactID})";
     }
     return NULL;
 }
Exemplo n.º 30
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $this->_showRelatedCases = CRM_Utils_Array::value('relatedCases', $_GET);
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
     $this->assign('multiClient', $isMultiClient);
     //pull the related cases.
     $this->assign('showRelatedCases', FALSE);
     if ($this->_showRelatedCases) {
         $relatedCases = $this->get('relatedCases');
         if (!isset($relatedCases)) {
             $cId = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject);
             $caseId = CRM_Utils_Request::retrieve('id', 'Integer', CRM_Core_DAO::$_nullObject);
             $relatedCases = CRM_Case_BAO_Case::getRelatedCases($caseId, $cId);
         }
         $this->assign('relatedCases', $relatedCases);
         $this->assign('showRelatedCases', TRUE);
         CRM_Utils_System::setTitle(ts('Related Cases'));
         return;
     }
     $this->_hasAccessToAllCases = CRM_Core_Permission::check('access all cases and activities');
     $this->assign('hasAccessToAllCases', $this->_hasAccessToAllCases);
     $this->assign('contactID', $this->_contactID = (int) $this->get('cid'));
     $this->assign('caseID', $this->_caseID = (int) $this->get('id'));
     // Access check.
     if (!CRM_Case_BAO_Case::accessCase($this->_caseID, FALSE)) {
         CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
     }
     $fulltext = CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject);
     if ($fulltext == 'fulltext') {
         $this->assign('fulltext', $fulltext);
     }
     $this->assign('contactType', CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'));
     $this->assign('userID', CRM_Core_Session::getLoggedInContactID());
     //retrieve details about case
     $params = array('id' => $this->_caseID);
     $returnProperties = array('case_type_id', 'subject', 'status_id', 'start_date');
     CRM_Core_DAO::commonRetrieve('CRM_Case_BAO_Case', $params, $values, $returnProperties);
     $statuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
     $caseTypeName = CRM_Case_BAO_Case::getCaseType($this->_caseID, 'name');
     $caseType = CRM_Case_BAO_Case::getCaseType($this->_caseID);
     $this->_caseDetails = array('case_type' => $caseType, 'case_status' => CRM_Utils_Array::value($values['case_status_id'], $statuses), 'case_subject' => CRM_Utils_Array::value('subject', $values), 'case_start_date' => $values['case_start_date']);
     $this->_caseType = $caseTypeName;
     $this->assign('caseDetails', $this->_caseDetails);
     $reportUrl = CRM_Utils_System::url('civicrm/case/report', "reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&asn=", FALSE, NULL, FALSE);
     $this->assign('reportUrl', $reportUrl);
     // add to recently viewed
     $url = CRM_Utils_System::url('civicrm/contact/view/case', "action=view&reset=1&id={$this->_caseID}&cid={$this->_contactID}&context=home");
     $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactID);
     $this->assign('displayName', $displayName);
     CRM_Utils_System::setTitle($displayName . ' - ' . $caseType);
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviCase', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/case', "action=delete&reset=1&id={$this->_caseID}&cid={$this->_contactID}&context=home");
     }
     // Add the recently viewed case
     CRM_Utils_Recent::add($displayName . ' - ' . $caseType, $url, $this->_caseID, 'Case', $this->_contactID, NULL, $recentOther);
     //get the related cases for given case.
     $relatedCases = $this->get('relatedCases');
     if (!isset($relatedCases)) {
         $relatedCases = CRM_Case_BAO_Case::getRelatedCases($this->_caseID, $this->_contactID);
         $relatedCases = empty($relatedCases) ? FALSE : $relatedCases;
         $this->set('relatedCases', $relatedCases);
     }
     $this->assign('hasRelatedCases', (bool) $relatedCases);
     if ($relatedCases) {
         $this->assign('relatedCaseLabel', ts('%1 Related Case', array('count' => count($relatedCases), 'plural' => '%1 Related Cases')));
         $this->assign('relatedCaseUrl', CRM_Utils_System::url('civicrm/contact/view/case', array('id' => $this->_caseID, 'cid' => $this->_contactID, 'relatedCases' => 1, 'action' => 'view')));
     }
     $entitySubType = !empty($values['case_type_id']) ? $values['case_type_id'] : NULL;
     $this->assign('caseTypeID', $entitySubType);
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Case', $this, $this->_caseID, NULL, $entitySubType);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->_caseID);
 }