/**
  * This function checks that if the given extension has provided Fields,
  * Data Sources or Events, that they aren't in use before the extension
  * is uninstalled or disabled. This prevents exceptions from occurring when
  * accessing an object that was using something provided by this Extension
  * can't anymore because it has been removed.
  *
  * @param Extension $obj
  *  An extension object
  * @return boolean
  */
 private static function __canUninstallOrDisable(Extension $obj)
 {
     $extension_handle = strtolower(preg_replace('/^extension_/i', NULL, get_class($obj)));
     $about = self::about($extension_handle);
     // Fields:
     if (is_dir(EXTENSIONS . "/{$extension_handle}/fields")) {
         foreach (glob(EXTENSIONS . "/{$extension_handle}/fields/field.*.php") as $file) {
             $type = preg_replace(array('/^field\\./i', '/\\.php$/i'), NULL, basename($file));
             if (FieldManager::isFieldUsed($type)) {
                 throw new Exception(__('The field ‘%s’, provided by the Extension ‘%s’, is currently in use.', array(basename($file), $about['name'])) . ' ' . __("Please remove it from your sections prior to uninstalling or disabling."));
             }
         }
     }
     // Data Sources:
     if (is_dir(EXTENSIONS . "/{$extension_handle}/data-sources")) {
         foreach (glob(EXTENSIONS . "/{$extension_handle}/data-sources/data.*.php") as $file) {
             $handle = preg_replace(array('/^data\\./i', '/\\.php$/i'), NULL, basename($file));
             if (PageManager::isDataSourceUsed($handle)) {
                 throw new Exception(__('The Data Source ‘%s’, provided by the Extension ‘%s’, is currently in use.', array(basename($file), $about['name'])) . ' ' . __("Please remove it from your pages prior to uninstalling or disabling."));
             }
         }
     }
     // Events
     if (is_dir(EXTENSIONS . "/{$extension_handle}/events")) {
         foreach (glob(EXTENSIONS . "/{$extension_handle}/events/event.*.php") as $file) {
             $handle = preg_replace(array('/^event\\./i', '/\\.php$/i'), NULL, basename($file));
             if (PageManager::isEventUsed($handle)) {
                 throw new Exception(__('The Event ‘%s’, provided by the Extension ‘%s’, is currently in use.', array(basename($file), $about['name'])) . ' ' . __("Please remove it from your pages prior to uninstalling or disabling."));
             }
         }
     }
     // Text Formatters
     if (is_dir(EXTENSIONS . "/{$extension_handle}/text-formatters")) {
         foreach (glob(EXTENSIONS . "/{$extension_handle}/text-formatters/formatter.*.php") as $file) {
             $handle = preg_replace(array('/^formatter\\./i', '/\\.php$/i'), NULL, basename($file));
             if (FieldManager::isTextFormatterUsed($handle)) {
                 throw new Exception(__('The Text Formatter ‘%s’, provided by the Extension ‘%s’, is currently in use.', array(basename($file), $about['name'])) . ' ' . __("Please remove it from your fields prior to uninstalling or disabling."));
             }
         }
     }
 }
 public function __viewIndex()
 {
     $this->setPageType('table');
     $this->setTitle(__('%1$s – %2$s', array(__('Symphony'), __('Member Roles'))));
     if (!FieldManager::isFieldUsed(extension_Members::getFieldType('role'))) {
         $this->pageAlert(__('There are no Member: Role fields in this Symphony installation. <a href="%s">Add Member: Role field?</a>', array(SYMPHONY_URL . '/blueprints/sections/')), Alert::NOTICE);
     }
     $this->appendSubheading(__('Member Roles'), Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL() . 'new/', __('Create a Role'), 'create button', NULL, array('accesskey' => 'c')));
     $roles = RoleManager::fetch();
     // Find all possible member sections
     $config_sections = explode(',', extension_Members::getSetting('section'));
     $aTableHead = array(array(__('Name'), 'col'));
     $aTableBody = array();
     if (!is_array($roles) || empty($roles)) {
         $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('None found.'), 'inactive', NULL, count($aTableHead)))));
     } else {
         if (empty($config_sections)) {
             $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('No Member sections exist in Symphony. <a href="%s">Create a Section?</a>', array(SYMPHONY_URL . '/blueprints/sections/')), 'inactive', NULL, count($aTableHead)))));
         } else {
             $hasRoles = FieldManager::isFieldUsed(extension_Members::getFieldType('role'));
             $roleFields = FieldManager::fetch(null, null, 'ASC', 'sortorder', extension_Members::getFieldType('role'));
             $with_selected_roles = array();
             $i = 0;
             foreach ($roles as $role) {
                 // Setup each cell
                 $td1 = Widget::TableData(Widget::Anchor($role->get('name'), Administration::instance()->getCurrentPageURL() . 'edit/' . $role->get('id') . '/', null, 'content'));
                 if ($role->get('id') != Role::PUBLIC_ROLE) {
                     $td1->appendChild(Widget::Input("items[{$role->get('id')}]", null, 'checkbox'));
                 }
                 // Get the number of members for this role, as long as it's not the Public Role.
                 if ($hasRoles && $role->get('id') != Role::PUBLIC_ROLE) {
                     $columns = array($td1);
                     foreach ($roleFields as $roleField) {
                         $section = SectionManager::fetch($roleField->get('parent_section'));
                         $member_count = Symphony::Database()->fetchVar('count', 0, sprintf("SELECT COUNT(*) AS `count` FROM `tbl_entries_data_%d` WHERE `role_id` = %d", $roleField->get('id'), $role->get('id')));
                         // If it's the first time we're looping over the available sections
                         // then change the table header, otherwise just ignore it as it's
                         // been done before
                         if ($i === 1) {
                             $aTableHead[] = array($section->get('name'), 'col');
                         }
                         $columns[] = Widget::TableData(Widget::Anchor("{$member_count}", SYMPHONY_URL . '/publish/' . $section->get('handle') . '/?filter=' . $roleField->get('element_name') . ':' . $role->get('id')));
                     }
                     $aTableBody[] = Widget::TableRow($columns);
                 } else {
                     if ($role->get('id') == Role::PUBLIC_ROLE) {
                         $td2 = Widget::TableData(__('This is the role assumed by the general public.'));
                     } else {
                         $td2 = Widget::TableData(__('None'), 'inactive');
                     }
                 }
                 // Add cells to a row
                 if ($i === 0) {
                     $aTableBody[] = Widget::TableRow(array($td1, $td2));
                 }
                 if ($hasRoles && $role->get('id') != Role::PUBLIC_ROLE) {
                     $with_selected_roles[] = array("move::" . $role->get('id'), false, $role->get('name'));
                 }
                 $i++;
             }
         }
     }
     $table = Widget::Table(Widget::TableHead($aTableHead), NULL, Widget::TableBody($aTableBody), 'selectable');
     $this->Form->appendChild($table);
     $tableActions = new XMLElement('div');
     $tableActions->setAttribute('class', 'actions');
     $options = array(0 => array(null, false, __('With Selected...')), 2 => array('delete', false, __('Delete'), 'confirm'), 3 => array('delete-members', false, __('Delete Members'), 'confirm'));
     if (count($with_selected_roles) > 0) {
         $options[1] = array('label' => __('Move Members To'), 'options' => $with_selected_roles);
     }
     $tableActions->appendChild(Widget::Apply($options));
     $this->Form->appendChild($tableActions);
 }
 /**
  * This function will ensure that the user who has submitted the form (and
  * hence is requesting that an event be triggered) is actually allowed to
  * do this request.
  * There are 2 action types, creation and editing. Creation is a simple yes/no
  * affair, whereas editing has three levels of permission, None, Own Entries
  * or All Entries:
  * - None: This user can't do process this event
  * - Own Entries: If the entry the user is trying to update is their own
  *   determined by if the `entry_id` or, in the case of a SBL or
  *   similar field, the `entry_id` of the linked entry matches the logged in
  *   user's id, process the event.
  * - All Entries: The user can update any entry in Symphony.
  * If there are no Roles in this system, or the event is set to ignore permissions
  * (by including a function, `ignoreRolePermissions` that returns `true`, it will
  * immediately proceed to processing any of the Filters attached to the event
  * before returning.
  *
  * @uses EventPreSaveFilter
  *
  * @param array $context
  * @return null
  */
 public function checkEventPermissions(array &$context)
 {
     // If this system has no Roles, or the event is set to ignore role permissions
     // continue straight to processing the Filters
     if (!FieldManager::isFieldUsed(extension_Members::getFieldType('role')) || method_exists($context['event'], 'ignoreRolePermissions') && $context['event']->ignoreRolePermissions() == true) {
         $this->__processEventFilters($context);
         return null;
     }
     // Prior to Symphony 2.2.2, the EventPreSaveFilter delegate doesn't
     // pass the `$entry_id`. This can cause an issue when an Event has the
     // `allow_multiple` filter set as we can't determine the correct `$entry_id`
     // This will check to see if the `$entry_id` is set, otherwise fallback
     // to the previous logic. This will mean that using `allow_multiple` will
     // not be compatible without Symphony 2.2.2 and Members 1.1
     // @see https://github.com/symphonycms/members/issues/167
     if (isset($context['entry_id']) && is_numeric($context['entry_id'])) {
         $entry_id = (int) $context['entry_id'];
         $action = 'edit';
     } else {
         if (isset($_POST['id']) && !empty($_POST['id'])) {
             $entry_id = (int) $_POST['id'];
             $action = 'edit';
         } else {
             $action = 'create';
             $entry_id = 0;
         }
     }
     $required_level = $action == 'create' ? EventPermissions::CREATE : EventPermissions::ALL_ENTRIES;
     $role_id = Role::PUBLIC_ROLE;
     $isLoggedIn = $this->getMemberDriver()->isLoggedIn();
     if ($isLoggedIn && $this->getMemberDriver()->initialiseMemberObject()) {
         if ($this->getMemberDriver()->getMember() instanceof Entry) {
             $required_level = EventPermissions::OWN_ENTRIES;
             $role_data = $this->getMemberDriver()->getMember()->getData(extension_Members::getField('role')->get('id'));
             $role_id = $role_data['role_id'];
             if ($action == 'edit' && method_exists($context['event'], 'getSource')) {
                 $section_id = $context['event']->getSource();
                 $isOwner = false;
                 // If the event is the same section as the Members section, then for `$isOwner`
                 // to be true, the `$entry_id` must match the currently logged in user.
                 if ($section_id == $this->getMemberDriver()->getMember()->get('section_id')) {
                     // Check the logged in member is the same as the `entry_id` that is about to
                     // be updated. If so the user is the Owner and can modify EventPermissions::OWN_ENTRIES
                     $isOwner = $this->getMemberDriver()->getMemberID() == $entry_id;
                 } else {
                     $field_ids = array();
                     // Get the ID's of the fields that may be used for Linking (Username/Email)
                     if (!is_null(extension_Members::getFieldHandle('identity'))) {
                         $field_ids[] = extension_Members::getField('identity')->get('id');
                     }
                     if (!is_null(extension_Members::getFieldHandle('email'))) {
                         $field_ids[] = extension_Members::getField('email')->get('id');
                     }
                     // Query for the `field_id` of any linking fields that link to the members
                     // section AND to one of the linking fields (Username/Email)
                     $fields = Symphony::Database()->fetchCol('child_section_field_id', sprintf("\n\t\t\t\t\t\t\t\t\tSELECT `child_section_field_id`\n\t\t\t\t\t\t\t\t\tFROM `tbl_sections_association`\n\t\t\t\t\t\t\t\t\tWHERE `parent_section_id` = %d\n\t\t\t\t\t\t\t\t\tAND `child_section_id` = %d\n\t\t\t\t\t\t\t\t\tAND `parent_section_field_id` IN ('%s')\n\t\t\t\t\t\t\t\t", $this->getMemberDriver()->getMember()->get('section_id'), $section_id, implode("','", $field_ids)));
                     // If there was a link found, get the `relation_id`, which is the `member_id` of
                     // an entry in the active Members section.
                     if (!empty($fields)) {
                         foreach ($fields as $field_id) {
                             if ($isOwner === true) {
                                 break;
                             }
                             $field = FieldManager::fetch($field_id);
                             if ($field instanceof Field) {
                                 // So we are trying to find all entries that have selected the Member entry
                                 // to determine ownership. This check will use the `fetchAssociatedEntryIDs`
                                 // function, which typically works backwards, by accepting the `entry_id` (in
                                 // this case, our logged in Member ID). This will return an array of all the
                                 // linked entries, so we then just check that the current entry that is going to
                                 // be updated is in that array
                                 $member_id = $field->fetchAssociatedEntryIDs($this->getMemberDriver()->getMemberID());
                                 $isOwner = in_array($entry_id, $member_id);
                             }
                         }
                     }
                 }
                 // User is not the owner, so they can edit EventPermissions::ALL_ENTRIES
                 if ($isOwner === false) {
                     $required_level = EventPermissions::ALL_ENTRIES;
                 }
             }
         }
     }
     $role = RoleManager::fetch($role_id);
     $event_handle = strtolower(preg_replace('/^event/i', NULL, get_class($context['event'])));
     $success = false;
     if ($role) {
         $success = $role->canProcessEvent($event_handle, $action, $required_level) ? true : false;
     }
     $context['messages'][] = array('permission', $success, $success === false ? __('You are not authorised to perform this action.') : null);
     // Process the Filters for this event.
     $this->__processEventFilters($context);
 }
 public function fetchMemberFromID($member_id = null)
 {
     $member = parent::fetchMemberFromID($member_id);
     if (is_null($member)) {
         return null;
     }
     // If the member isn't activated and a Role field exists, we need to override
     // the current Role with the Activation Role. This may allow Members to view certain
     // things until they active their account.
     if (!is_null($this->section->getFieldHandle('activation'))) {
         if ($member->getData($this->section->getField('activation')->get('id'), true)->activated != "yes") {
             if (FieldManager::isFieldUsed($this->section->getFieldHandle('role'))) {
                 $member->setData($this->section->getField('role')->get('id'), $this->section->getField('activation')->get('activation_role_id'));
             }
         }
     }
     return $member;
 }