/**
  *	
  * @param array $permissions with the member and the changed_pgs
  */
 function afterMemberPermissionChanged($permissions)
 {
     $member = array_var($permissions, 'member');
     //get all users in the set of permissions groups
     $permissionGroupIds = array();
     foreach (array_var($permissions, 'changed_pgs') as $pg_id) {
         $permissionGroupId = $pg_id;
         if (!in_array($permissionGroupId, $permissionGroupIds)) {
             $permissionGroupIds[] = $permissionGroupId;
         }
     }
     if (count($permissionGroupIds) > 0) {
         $usersIds = ContactPermissionGroups::getAllContactsIdsByPermissionGroupIds($permissionGroupIds);
         foreach ($usersIds as $us_id) {
             $user = Contacts::findById($us_id);
             ContactMemberCaches::updateContactMemberCache($user, $member->getId());
         }
     } else {
         //update this member for all user in cache
         $contacts = Contacts::getAllUsers();
         foreach ($contacts as $contact) {
             ContactMemberCaches::updateContactMemberCache($contact, $member->getId());
         }
     }
 }
 /**
  * Returns the parent member cache or null if there isn't one
  * @return Member
  */
 function getParentMemberCache()
 {
     if ($this->parent_member_cache == null) {
         if ($this->getParentMemberId() != 0) {
             $id = array('contact_id' => $this->getContactId(), 'member_id' => $this->getParentMemberId());
             $this->parent_member_cache = ContactMemberCaches::findById($id);
         }
     }
     return $this->parent_member_cache;
 }
Example #3
0
/**
 * Contact member cache
 *
 */
function core_dimensions_update_7_8()
{
    //UPDATE depth for all members
    //update root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 1  WHERE parent_member_id = 0;");
    //clean root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 2  WHERE parent_member_id != 0 AND depth = 1;");
    $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE parent_member_id =0 ORDER BY id");
    $members_depth = array_flat($members_depth);
    $members_depth = implode(",", $members_depth);
    $depth = 2;
    $max_depth = DB::executeOne("SELECT  MAX(depth) AS depth FROM `" . TABLE_PREFIX . "members`");
    //update all depths
    for ($i = $depth; $i <= $max_depth['depth']; $i++) {
        //update members depth
        DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = " . $depth . " WHERE parent_member_id  IN (" . $members_depth . ");");
        //Get member from next depth
        $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE depth= " . $depth . " ORDER BY id");
        $members_depth = array_flat($members_depth);
        $members_depth = implode(",", $members_depth);
        $depth++;
    }
    //END UPDATE depth for all members
    //Load the contact member cache
    set_time_limit(0);
    ini_set('memory_limit', '512M');
    $users = Contacts::getAllUsers();
    $dimensions = Dimensions::findAll();
    $dimensions_ids = array();
    foreach ($dimensions as $dimension) {
        if ($dimension->getDefinesPermissions()) {
            $dimensions_ids[] = $dimension->getId();
        }
    }
    $dimensions_ids = implode(",", $dimensions_ids);
    $root_members = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id IN (" . $dimensions_ids . ") AND parent_member_id=0 ORDER BY id");
    foreach ($users as $user) {
        try {
            DB::beginWork();
            foreach ($root_members as $member) {
                ContactMemberCaches::updateContactMemberCache($user, $member['id'], $member['parent_member_id']);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }
    //END Load the contact member cache
}
 function buildMemberList($all_members, $dimension, $allowed_member_type_ids, $allowed_object_type_ids, $item_object, $object_type_id, $return_only_name = false)
 {
     $dot_array = array();
     // Dimension Object Types array (cache)
     $membersset = array();
     foreach ($all_members as $m) {
         $membersset[$m->getId()] = true;
     }
     $members = array();
     foreach ($all_members as $m) {
         /* @var  $m Member */
         //		if ($m->getArchivedById() > 0) continue;
         if ($object_type_id != null) {
             $selectable = in_array($m->getObjectTypeId(), $allowed_object_type_ids) ? true : false;
             if ($selectable && isset($item_object)) {
                 if (!$item_object->canAdd(logged_user(), array($m))) {
                     continue;
                 }
             }
         } else {
             $selectable = true;
         }
         if (count($allowed_member_type_ids) && !in_array($m->getObjectTypeId(), $allowed_member_type_ids)) {
             continue;
         }
         $tempParent = $m->getParentMemberId();
         //check if have parent member id from Contact Member Cache
         if (isset($m->cached_parent_member_id)) {
             $tempParent = $m->cached_parent_member_id;
         } else {
             if (!logged_user()->isAdministrator()) {
                 $x = $m;
                 while ($x instanceof Member && !isset($membersset[$tempParent])) {
                     $tempParent = $x->getParentMemberId();
                     if ($x->getParentMemberId() == 0) {
                         break;
                     }
                     $x = $x->getParentMember();
                 }
                 if (!$x instanceof Member) {
                     $tempParent = 0;
                 }
             } else {
                 $tempParent = $m->getParentMemberId();
             }
         }
         $memberOptions = '';
         // SET member options (dimension object types table)
         // CHeck dot cache, if not set goto database and add to cache
         if (empty($dot_array[$dimension->getId()]) || empty($dot_array[$dimension->getId()][$m->getObjectTypeId()])) {
             $dot = DimensionObjectTypes::instance()->findOne(array("conditions" => "dimension_id = " . $dimension->getId() . " AND object_type_id = " . $m->getObjectTypeId()));
             if ($dot instanceof DimensionObjectType) {
                 if (empty($dot_array['dimension_id'])) {
                     $dot_array[$dimension->getId()] = array();
                 }
                 $dot_array[$dimension->getId()][$m->getObjectTypeId()] = $dot;
             }
         }
         if (!empty($dot_array[$dimension->getId()]) || $dot_array[$dimension->getId()][$m->getObjectTypeId()] instanceof DimensionObjectType) {
             $dot = $dot_array[$dimension->getId()][$m->getObjectTypeId()];
             if ($dot) {
                 $memberOptions = $dot->getOptions(true);
             }
         }
         if ($return_only_name) {
             $path = trim($m->getPath());
             $member = array("id" => $m->getId(), "name" => $m->getName(), "path" => $path, "depth" => $m->getDepth(), "to_show" => $m->getName() . ($path != "" ? " ({$path})" : ""), "dim" => $m->getDimensionId(), "ico" => "ico-color" . $m->getColor() . " " . $m->getIconClass());
         } else {
             //Do not use contact member cache for superadmins
             if (!logged_user()->isAdministrator()) {
                 //check childs from contact member cache
                 $childsIds = ContactMemberCaches::getAllChildrenIdsFromCache(logged_user()->getId(), $m->getId());
             } else {
                 $childsIds = $m->getAllChildrenIds(false, null, "");
             }
             $totalChilds = count($childsIds);
             $haveChilds = $totalChilds > 0 ? true : false;
             /* @var $m Member */
             $additional_member_class = "";
             Hook::fire('additional_member_node_class', $m, $additional_member_class);
             $member = array("id" => $m->getId(), "color" => $m->getMemberColor(), "name" => clean($m->getName()), "text" => clean($m->getName()), "leaf" => true, "parent" => $tempParent, "realParent" => $m->getParentMemberId(), "object_id" => $m->getObjectId(), "options" => $memberOptions, "depth" => $m->getDepth(), "cls" => $additional_member_class, "iconCls" => "ico-color" . $m->getColor() . " " . $m->getIconClass(), "selectable" => isset($selectable) ? $selectable : false, "dimension_id" => $m->getDimensionId(), "object_type_id" => $m->getObjectTypeId(), "expandable" => $haveChilds, "realTotalChilds" => $totalChilds, "allow_childs" => $m->allowChilds());
             // Member Actions
             if (can_manage_dimension_members(logged_user())) {
                 $editUrl = '';
                 // If member has an object linked, take object edit url
                 if ($ot = ObjectTypes::findById($m->getObjectTypeId())) {
                     if ($handler = $ot->getHandlerClass()) {
                         eval("\$itemClass = {$handler}::instance()->getItemClass();");
                         if ($itemClass) {
                             $instance = new $itemClass();
                             $instance->setId($m->getObjectId());
                             $instance->setObjectId($m->getObjectId());
                             if ($instance instanceof Contact) {
                                 if ($ot->getName() == 'company') {
                                     $instance->setIsCompany(1);
                                 }
                             }
                             $editUrl = $instance->getEditUrl();
                         }
                     }
                 }
                 // Take default membewr edit url if not overwitten
                 if (!$editUrl) {
                     $editUrl = get_url('member', 'edit', array('id' => $m->getId()));
                 }
                 $member['actions'] = array(array('url' => $editUrl, 'text' => '', 'iconCls' => 'ico-edit', 'class' => 'action-edit'));
             }
         }
         $members[] = $member;
     }
     // re-sort by parent and name
     $tmp_members = array();
     foreach ($members as $m) {
         $tmp_members[str_pad(array_var($m, 'depth'), 20, "0", STR_PAD_LEFT) . strtolower(array_var($m, 'name')) . array_var($m, 'id')] = $m;
     }
     ksort($tmp_members, SORT_STRING);
     $members = $tmp_members;
     return $members;
 }
 /**
  * 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, 'ContactMemberCaches')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return ContactMemberCaches::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 /**
  * Edit specific contact
  *
  * @access public
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('edit_contact');
     $contact = Contacts::findById(get_id());
     if (!$contact instanceof Contact) {
         flash_error(lang('contact dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$contact->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     // telephone types
     $all_telephone_types = TelephoneTypes::getAllTelephoneTypesInfo();
     tpl_assign('all_telephone_types', $all_telephone_types);
     // address types
     $all_address_types = AddressTypes::getAllAddressTypesInfo();
     tpl_assign('all_address_types', $all_address_types);
     // webpage types
     $all_webpage_types = WebpageTypes::getAllWebpageTypesInfo();
     tpl_assign('all_webpage_types', $all_webpage_types);
     // email types
     $all_email_types = EmailTypes::getAllEmailTypesInfo();
     tpl_assign('all_email_types', $all_email_types);
     $contact_data = array_var($_POST, 'contact');
     // Populate form fields
     if (!is_array($contact_data)) {
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
         $contact_data = $this->get_contact_data_from_contact($contact);
         if ($contact->isUser()) {
             $_REQUEST['is_user'] = 1;
             tpl_assign('user_type', $contact->getUserType());
         }
         if (is_array($im_types)) {
             foreach ($im_types as $im_type) {
                 $contact_data['im_' . $im_type->getId()] = $contact->getImValue($im_type);
             }
             // foreach
         }
         // if
         $null = null;
         Hook::fire('before_edit_contact_form', array('object' => $contact), $null);
     }
     // if
     tpl_assign('isEdit', array_var($_GET, 'isEdit', false));
     tpl_assign('contact', $contact);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('im_types', $im_types);
     tpl_assign('active_tab', array_var($_REQUEST, 'active_tab'));
     //Contact Submit
     if (is_array(array_var($_POST, 'contact'))) {
         foreach ($contact_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         try {
             DB::beginWork();
             $contact_data['email'] = trim($contact_data['email']);
             $contact_data['contact_type'] = 'contact';
             Contacts::validate($contact_data, get_id());
             $newCompany = false;
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 $company_data = array_var($_POST, 'company');
                 $company_data['contact_type'] = 'company';
                 Contacts::validate($company_data);
                 $company = new Contact();
                 $company->setFromAttributes($company_data);
                 $company->setIsCompany(true);
                 $company->setObjectName();
                 $company->save();
                 // save phones, addresses and webpages
                 $this->save_phones_addresses_webpages($company_data, $company);
                 if ($company_data['email'] != "") {
                     $company->addEmail($company_data['email'], 'work', true);
                 }
                 $newCompany = true;
             }
             $contact_data['birthday'] = getDateValue($contact_data["birthday"]);
             if (isset($contact_data['specify_username'])) {
                 if ($contact_data['user']['username'] != "") {
                     $contact_data['name'] = $contact_data['user']['username'];
                 } else {
                     $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname'];
                 }
             } else {
                 $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname'];
             }
             $user_data = array_var($_POST, 'user');
             if (is_array($user_data) && trim(array_var($user_data, 'username', '')) != "") {
                 $contact_data['username'] = trim(array_var($user_data, 'username', ''));
             }
             $contact->setFromAttributes($contact_data);
             if ($newCompany) {
                 $contact->setCompanyId($company->getId());
             }
             $contact->setObjectName();
             $contact->save();
             // save phones, addresses and webpages
             $this->save_phones_addresses_webpages($contact_data, $contact);
             //Emails
             $personal_email_type_id = EmailTypes::getEmailTypeId('personal');
             $main_emails = $contact->getMainEmails();
             $more_main_emails = array();
             $main_mail = null;
             foreach ($main_emails as $me) {
                 if ($main_mail == null) {
                     $main_mail = $me;
                 } else {
                     $more_main_emails[] = $me;
                 }
             }
             if ($main_mail) {
                 $main_mail->editEmailAddress($contact_data['email']);
             } else {
                 if ($contact_data['email'] != "") {
                     $contact->addEmail($contact_data['email'], 'personal', true);
                 }
             }
             foreach ($more_main_emails as $mme) {
                 $mme->setIsMain(false);
                 $mme->save();
             }
             // save additional emails
             $this->save_non_main_emails($contact_data, $contact);
             // autodetect timezone
             $autotimezone = array_var($contact_data, 'autodetect_time_zone', null);
             if ($autotimezone !== null) {
                 set_user_config_option('autodetect_time_zone', $autotimezone, $contact->getId());
             }
             // IM values
             $contact->clearImValues();
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $contact_im_value = new ContactImValue();
                     $contact_im_value->setContactId($contact->getId());
                     $contact_im_value->setImTypeId($im_type->getId());
                     $contact_im_value->setValue($value);
                     $contact_im_value->setIsMain(array_var($contact_data, 'default_im') == $im_type->getId());
                     $contact_im_value->save();
                 }
                 // if
             }
             // foreach
             $member_ids = json_decode(array_var($_POST, 'members'));
             $object_controller = new ObjectController();
             if (!is_null($member_ids)) {
                 $object_controller->add_to_members($contact, $member_ids);
             }
             $no_perm_members_ids = json_decode(array_var($_POST, 'no_perm_members'));
             if (count($no_perm_members_ids)) {
                 $object_controller->add_to_members($contact, $no_perm_members_ids);
             }
             if ($newCompany) {
                 $object_controller->add_to_members($company, $member_ids);
             }
             $object_controller->link_to_new_object($contact);
             $object_controller->add_subscribers($contact);
             $object_controller->add_custom_properties($contact);
             // User settings
             $user = array_var(array_var($_POST, 'contact'), 'user');
             if ($user && $contact->canUpdatePermissions(logged_user())) {
                 $user_type_changed = false;
                 if (array_var($user, 'type')) {
                     $user_type_changed = $contact->getUserType() != array_var($user, 'type');
                     $contact->setUserType(array_var($user, 'type'));
                     $contact->save();
                 }
                 if ($user_type_changed) {
                     $this->cut_max_user_permissions($contact);
                 }
                 // update user groups
                 if (isset($_REQUEST['user_groups'])) {
                     $insert_values = "";
                     $group_ids = explode(',', $_REQUEST['user_groups']);
                     foreach ($group_ids as $gid) {
                         if (trim($gid) == "" || !is_numeric($gid)) {
                             continue;
                         }
                         $insert_values .= ($insert_values == "" ? "" : ",") . "(" . $contact->getId() . ", {$gid})";
                     }
                     ContactPermissionGroups::instance()->delete("contact_id=" . $contact->getId() . " AND permission_group_id <> " . $contact->getPermissionGroupId());
                     if ($insert_values != "") {
                         DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_permission_groups VALUES {$insert_values} ON DUPLICATE KEY UPDATE contact_id=contact_id;");
                     }
                     ContactMemberCaches::updateContactMemberCacheAllMembers($contact);
                 }
             }
             $null = null;
             Hook::fire('after_edit_contact', $contact, $null);
             DB::commit();
             // save user permissions
             if ($user && $contact->canUpdatePermissions(logged_user())) {
                 save_user_permissions_background(logged_user(), $contact->getPermissionGroupId(), $contact->isGuest());
             }
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD);
             }
             ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_EDIT);
             flash_success(lang('success edit contact', $contact->getObjectName()));
             ajx_current("back");
             if (array_var($_REQUEST, 'modal')) {
                 evt_add("reload current panel");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
    $depth++;
}
//END UPDATE depth for all members
echo "\nStart Truncate  contact_member_cache\n-----------------------------------------------------------------";
DB::execute("TRUNCATE TABLE " . TABLE_PREFIX . "contact_member_cache;");
echo "\nEnd Truncate  contact_member_cache\n-----------------------------------------------------------------";
$users = Contacts::getAllUsers();
$dimensions = Dimensions::findAll();
$dimensions_ids = array();
foreach ($dimensions as $dimension) {
    if ($dimension->getDefinesPermissions()) {
        $dimensions_ids[] = $dimension->getId();
    }
}
$dimensions_ids = implode(",", $dimensions_ids);
$root_members = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id IN (" . $dimensions_ids . ") AND parent_member_id=0 ORDER BY id");
foreach ($users as $user) {
    echo "\n" . $user->getName();
    try {
        DB::beginWork();
        foreach ($root_members as $member) {
            ContactMemberCaches::updateContactMemberCache($user, $member['id'], $member['parent_member_id']);
        }
        DB::commit();
    } catch (Exception $e) {
        DB::rollback();
        echo $e->__toString();
    }
}
//END Load the contact member cache
echo "\nEnd rebuild  contact_member_cache\n-----------------------------------------------------------------";
 function manager()
 {
     if (!$this->manager instanceof ContactMemberCaches) {
         $this->manager = ContactMemberCaches::instance();
     }
     return $this->manager;
 }