Esempio n. 1
0
    /**
     * Return an array of items to show in the your account panel
     *
     * @return   array
     */
    public function getall($args)
    {
        $items = array();
        $uname = (isset($args['uname'])) ? $args['uname'] : UserUtil::getVar('uname');
        // does this user exist?
        if(UserUtil::getIdFromName($uname)==false) {
            // user does not exist
            return $items;
        }

        // Create an array of links to return
        if (SecurityUtil::checkPermission('News::', '::', ACCESS_COMMENT)) {
            $items[] = array('url'     => ModUtil::url('News', 'user', 'newitem'),
                    'module'  => 'News',
                    'title'   => $this->__('Submit an article'),
                    'icon'    => 'news_add.gif');

            /* If users can save draft articles and the viewdraft function is implemented, this can be enabled
        $items[] = array('url'     => ModUtil::url('News', 'user', 'viewdraft'),
                         'module'  => 'News',
                         'title'   => __('View personal draft articles', $dom),
                         'icon'    => 'news_draft.gif');
            */

        }

        // Return the items
        return $items;
    }
/**
 * Zikula_View function to get the user id for a given user.
 *
 * This function will return the user ID for a given username.
 *
 * available parameters:
 *  - uname       the username return the id for
 *  - assign      if set, the language will be assigned to this variable
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string The user ID.
 */
function smarty_function_usergetidfromname($params, Zikula_View $view)
{
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $uname = isset($params['uname']) ? $params['uname'] : null;
    if (!$uname) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('usergetidfromname', 'uname')));
        return false;
    }
    $return = UserUtil::getIdFromName($uname);
    if ($assign) {
        $view->assign($assign, $return);
    } else {
        return $return;
    }
}
Esempio n. 3
0
 /**
  * Return an array of items to show in the your account panel
  *
  * @return   array
  */
 public function getall($args)
 {
     $items = array();
     $uname = isset($args['uname']) ? $args['uname'] : UserUtil::getVar('uname');
     // does this user exist?
     if (UserUtil::getIdFromName($uname) == false) {
         // user does not exist
         return $items;
     }
     // Create an array of links to return
     if (SecurityUtil::checkPermission('Content::', '::', ACCESS_EDIT)) {
         $items[] = array('url' => ModUtil::url('Content', 'admin', 'newpage'), 'module' => 'Content', 'title' => $this->__('Add a new page'), 'icon' => 'content_add.gif');
     }
     // Return the items
     return $items;
 }
 public function addSearch($s)
 {
     $search = $s['search'];
     $search_field = $s['search_field'];
     if ($search === false || $search_field === false) {
         return;
     }
     switch ($search_field) {
         case 'author':
             if (is_numeric($search)) {
                 return $this->filterAuthor($search);
             } elseif (is_string($search)) {
                 $uid = \UserUtil::getIdFromName($search);
                 $uid = $uid !== false ? $uid : 0;
                 return $this->filterAuthor($uid);
             }
             break;
         case 'name':
             return $this->andWhere('m.name LIKE :search')->setParameter('search', '%' . $search . '%');
     }
 }
/**
 * Zikula_View modifier to create a link to a users profile
 *
 * Example
 *
 *   Simple version, shows $username
 *   {$username|userprofilelink}
 *   Simple version, shows $username, using class="classname"
 *   {$username|userprofilelink:classname}
 *   Using profile.gif instead of username, no class
 *   {$username|userprofilelink:'':'images/profile.gif'}
 *
 *   Using language depending image from pnimg. Note that we pass
 *   the pnimg result array to the modifier as-is
 *   { pnimg src='profile.gif' assign=profile}
 *   {$username|userprofilelink:'classname':$profile}
 *
 * @param string  $string    The users name.
 * @param string  $class     The class name for the link (optional).
 * @param mixed   $image     The image to show instead of the username (optional).
 *                              May be an array as created by pnimg.
 * @param integer $maxLength If set then user names are truncated to x chars.
 *
 * @return string The output.
 */
function smarty_modifier_userprofilelink($string, $class = '', $image = '', $maxLength = 0)
{
    LogUtil::log(__f('Warning! Template modifier {$var|%1$s} is deprecated, please use {$var|%2$s} instead.', array('userprofilelink', 'profilelinkbyuname} {$var|profilelinkbyuid')), E_USER_DEPRECATED);
    // TODO - This does not handle cases where the uname is made up entirely of digits (e.g. $uname == "123456"). It will interpret it
    // as a uid. A new modifier is needed that acts on uids and only uids, and this modifier should act on unames and only unames.
    if (is_numeric($string)) {
        $uid = DataUtil::formatForStore($string);
        $uname = UserUtil::getVar('uname', $uid);
    } else {
        $uname = DataUtil::formatForStore($string);
        $uid = UserUtil::getIdFromName($uname);
    }
    $showUname = DataUtil::formatForDisplay($uname);
    $profileModule = System::getVar('profilemodule', '');
    if (isset($uid) && $uid && isset($uname) && $uname && $uid > 1 && !empty($profileModule) && ModUtil::available($profileModule) && strtolower($uname) != strtolower(ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_ANONYMOUS_DISPLAY_NAME))) {
        if (!empty($class)) {
            $class = ' class="' . DataUtil::formatForDisplay($class) . '"';
        }
        if (!empty($image)) {
            if (is_array($image)) {
                // if it is an array we assume that it is an pnimg array
                $show = '<img src="' . DataUtil::formatForDisplay($image['src']) . '" alt="' . DataUtil::formatForDisplay($image['alt']) . '" width="' . DataUtil::formatForDisplay($image['width']) . '" height="' . DataUtil::formatForDisplay($image['height']) . '" />';
            } else {
                $show = '<img src="' . DataUtil::formatForDisplay($image) . '" alt="' . $showUname . '" />';
            }
        } elseif ($maxLength > 0) {
            // truncate the user name to $maxLength chars
            $showLength = strlen($showUname);
            $truncEnd = $maxLength > $showLength ? $showLength : $maxLength;
            $showUname = substr($string, 0, $truncEnd);
        }
        $profileLink = '<a' . $class . ' title="' . DataUtil::formatForDisplay(__('Personal information')) . ': ' . $showUname . '" href="' . DataUtil::formatForDisplay(ModUtil::url($profileModule, 'user', 'view', array('uid' => $uid), null, null, true)) . '">' . $showUname . '</a>';
    } elseif (!empty($image)) {
        $profileLink = '';
        //image for anonymous user should be "empty"
    } else {
        $profileLink = DataUtil::formatForDisplay($string);
    }
    return $profileLink;
}
/**
 * Zikula_View modifier to create a link to a users profile from the username.
 *
 * Example
 *
 *   Simple version, shows $username
 *   {$username|profilelinkbyuname}
 *   Simple version, shows $username, using class="classname"
 *   {$username|profilelinkbyuname:classname}
 *   Using profile.gif instead of username, no class
 *   {$username|profilelinkbyuname:'':'images/profile.gif'}
 *
 *   Using language depending image from pnimg. Note that we pass
 *   the pnimg result array to the modifier as-is
 *   {img src='profile.gif' assign=profile}
 *   {$username|profilelinkbyuname:'classname':$profile}
 *
 * @param string  $string    The users name.
 * @param string  $class     The class name for the link (optional).
 * @param mixed   $image     The image to show instead of the username (optional).
 *                              May be an array as created by pnimg.
 * @param integer $maxLength If set then user names are truncated to x chars.
 *
 * @return string The output.
 */
function smarty_modifier_profilelinkbyuname($uname, $class = '', $image = '', $maxLength = 0)
{
    if (empty($uname)) {
        return $uname;
    }
    $uid = UserUtil::getIdFromName($uname);
    $profileModule = System::getVar('profilemodule', '');
    if ($uid && $uid > 1 && !empty($profileModule) && ModUtil::available($profileModule)) {
        $userDisplayName = ModUtil::apiFunc($profileModule, 'user', 'getUserDisplayName', array('uid' => $uid));
        if (empty($userDisplayName)) {
            $userDisplayName = $uname;
        }
        if (!empty($class)) {
            $class = ' class="' . DataUtil::formatForDisplay($class) . '"';
        }
        if (!empty($image)) {
            if (is_array($image)) {
                // if it is an array we assume that it is an img array
                $show = '<img src="' . DataUtil::formatForDisplay($image['src']) . '" alt="' . DataUtil::formatForDisplay($image['alt']) . '" width="' . DataUtil::formatForDisplay($image['width']) . '" height="' . DataUtil::formatForDisplay($image['height']) . '" />';
            } else {
                $show = '<img src="' . DataUtil::formatForDisplay($image) . '" alt="' . DataUtil::formatForDisplay($userDisplayName) . '" />';
            }
        } elseif ($maxLength > 0) {
            // truncate the user name to $maxLength chars
            $length = strlen($userDisplayName);
            $truncEnd = $maxLength > $length ? $length : $maxLength;
            $show = DataUtil::formatForDisplay(substr($userDisplayName, 0, $truncEnd));
        } else {
            $show = DataUtil::formatForDisplay($userDisplayName);
        }
        $profileLink = '<a' . $class . ' title="' . DataUtil::formatForDisplay(__('Profile')) . ': ' . DataUtil::formatForDisplay($userDisplayName) . '" href="' . DataUtil::formatForDisplay(ModUtil::url($profileModule, 'user', 'view', array('uid' => $uid), null, null, true)) . '">' . $show . '</a>';
    } elseif (!empty($image)) {
        $profileLink = '';
        // image for anonymous user should be "empty"
    } else {
        $profileLink = DataUtil::formatForDisplay($uname);
    }
    return $profileLink;
}
Esempio n. 7
0
 /**
  * Return an array of items to show in the your account panel.
  *
  * @param array $args List of arguments.
  *
  * @return array List of collected account items
  */
 public function getall(array $args = array())
 {
     // collect items in an array
     $items = array();
     $useAccountPage = $this->getVar('useAccountPage', true);
     if ($useAccountPage === false) {
         return $items;
     }
     $userName = isset($args['uname']) ? $args['uname'] : UserUtil::getVar('uname');
     // does this user exist?
     if (UserUtil::getIdFromName($userName) === false) {
         // user does not exist
         return $items;
     }
     if (!SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_OVERVIEW)) {
         return $items;
     }
     // Create an array of links to return
     if (SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_ADMIN)) {
         $items[] = array('url' => ModUtil::url($this->name, 'admin', 'main'), 'title' => $this->__('M u video Backend'), 'icon' => 'configure.png', 'module' => 'core', 'set' => 'icons/large');
     }
     // return the items
     return $items;
 }
Esempio n. 8
0
    /**
     * Return an array of items to show in the "user account page".
     * 
     * Parameters passed in the $args array:
     * -------------------------------------
     * string uname The user name of the user for whom links should be returned; optional, defaults to the current user.
     * 
     * @param array $args All parameters passed to this function.
     *
     * @return   array   array of items, or false on failure
     */
    public function getall($args)
    {

        $items = array();

        // do not show the account links if Profile is not the Profile manager
        $profilemodule = System::getVar('profilemodule', '');
        if ($profilemodule != 'Profile') {
            return $items;
        }

        $uname = isset($args['uname']) ? $args['uname'] : null;
        if (!$uname && UserUtil::isLoggedIn()) {
            $uname = UserUtil::getVar('uname');
        }

        // Create an array of links to return
        if (!empty($uname)) {
            $uid = UserUtil::getIdFromName($uname);
            $items['0'] = array('url'     => ModUtil::url('Profile', 'user', 'view', array('uid' => $uid)),
                    'module'  => 'Profile',
                    //! account panel link
                    'title'   => $this->__('Personal info'),
                    'icon'    => 'admin.png');

            if (SecurityUtil::checkPermission('Profile:Members:', '::', ACCESS_READ)) {
                $items['1'] = array('url'     => ModUtil::url('Profile', 'user', 'viewmembers'),
                        'module'  => 'Profile',
                        'title'   => $this->__('Registered users list'),
                        'icon'    => 'members.png');
            }
        }

        // Return the items
        return $items;
    }
Esempio n. 9
0
 /**
  * Test a permission rule for a given username
  *
  * @param test_user the username
  * @param test_component the component
  * @param test_instance the instance
  * @param test_level the accesslevel
  * @return string with test result for display
  */
 public function testpermission()
 {
     $this->checkAjaxToken();
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Permissions::', '::', ACCESS_ADMIN));
     $uname = $this->request->getPost()->get('test_user', '');
     $comp = $this->request->getPost()->get('test_component', '.*');
     $inst = $this->request->getPost()->get('test_instance', '.*');
     $level = $this->request->getPost()->get('test_level', ACCESS_READ);
     $result = $this->__('Permission check result:') . ' ';
     $uid = UserUtil::getIdFromName($uname);
     if ($uid == false) {
         $result .= '<span id="permissiontestinfored">' . $this->__('unknown user.') . '</span>';
     } else {
         if (SecurityUtil::checkPermission($comp, $inst, $level, $uid)) {
             $result .= '<span id="permissiontestinfogreen">' . $this->__('permission granted.') . '</span>';
         } else {
             $result .= '<span id="permissiontestinfored">' . $this->__('permission not granted.') . '</span>';
         }
     }
     return new Zikula_Response_Ajax(array('testresult' => $result));
 }
Esempio n. 10
0
    /**
     * submit a message
     *
     * @author       The PostNuke Development Team
     * @param        integer      $tid     the ID of the item to display
     * @return       output       The item detail page
     */
    public function submit($args) {
        $image = FormUtil::getPassedValue('image', isset($args['image']) ? $args['image'] : null, 'POST');
        $subject = FormUtil::getPassedValue('subject', isset($args['subject']) ? $args['subject'] : null, 'POST');
        $to_user = FormUtil::getPassedValue('to_user', isset($args['to_user']) ? $args['to_user'] : null, 'POST');
        $message = FormUtil::getPassedValue('message', isset($args['message']) ? $args['message'] : null, 'POST');
        $reply = FormUtil::getPassedValue('reply', isset($args['reply']) ? $args['reply'] : null, 'POST');
        $replied = FormUtil::getPassedValue('replied', isset($args['replied']) ? $args['replied'] : 0, 'POST');
        $file1 = FormUtil::getPassedValue('file1', isset($args['file1']) ? $args['file1'] : null, 'POST');
        $file2 = FormUtil::getPassedValue('file2', isset($args['file2']) ? $args['file2'] : null, 'POST');
        $file3 = FormUtil::getPassedValue('file3', isset($args['file3']) ? $args['file3'] : null, 'POST');
        $multi = FormUtil::getPassedValue('multi', isset($args['multi']) ? $args['multi'] : null, 'POST');
        if (!SecurityUtil::checkPermission('IWmessages::', $to_user . '::', ACCESS_COMMENT)) {
            throw new Zikula_Exception_Forbidden();
        }
        // Confirm authorisation code
        $this->checkCsrfToken();
        if (empty($to_user) && (!isset($multi) || $multi == '0')) {
            LogUtil::registerError($this->__('Not user especified.'));
            return System::redirect(ModUtil::url('IWmessages', 'user', 'view'));
        }
        if (empty($message)) {
            LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
            return System::redirect(ModUtil::url('IWmessages', 'user', 'view'));
        }
        $message = nl2br($message);
        if (empty($subject)) {
            $subject = $this->__('No subject');
        }
        if (UserUtil::isLoggedIn()) {
            $message .= "[addsig]";
        }
        //Create an array with the names of all the persons who are going to receipt the message
        $usersName = array();

        //parse the users for the message
        if (strpos($to_user, ',') != 0) {
            //More than a user separeted by ,
            $users = explode(',', $to_user);
            foreach ($users as $user) {
                if ($user != '') {
                    $usersName[] = $user;
                }
            }
        } else {
            //an alone user
            if ($to_user != '') {
                $usersName[] = $to_user;
            }
        }

        //Create an array with the ids of all the persons who are going to receipt the message
        $usersId = array();
        //For each user check if is a valid one.
        $noValidUser = '';
        foreach ($usersName as $userName) {
            // get the user id
            $to_userid = UserUtil::getIdFromName($userName);
            if (!$to_userid) {
                $noValidUser .= $userName . ' - ';
            } else {
                $usersId[] = $to_userid;
            }
        }
        if ($noValidUser != '') {
            $noValidUser = substr($noValidUser, 0, -3);
            LogUtil::registerError($this->__('Some of the users writed into the field A: are not correct. The incorrect users are: ') . $noValidUser);
            return System::redirect((UserUtil::isLoggedIn()) ? ModUtil::url('IWmessages', 'user', 'compose',
                                    array('touser' => $to_user,
                                        'subject' => $subject,
                                        'message' => str_replace('[addsig]', '', $message),
                                        'reply' => $reply,
                                        'to_group' => $multi,
                                        'image' => $image)) : 'index.php');
        }
        $groupsCanUpdate = ModUtil::getVar('IWmessages', 'groupsCanUpdate');
        $groupsUpdate = explode('$$', substr($groupsCanUpdate, 0, -1));
        array_shift($groupsUpdate);
        foreach ($groupsUpdate as $update) {
            $names = explode('|', $update);
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $isMember = ModUtil::func('IWmain', 'user', 'isMember',
                            array('uid' => UserUtil::getVar('uid'),
                                'gid' => $names[0],
                                'sgid' => $names[1],
                                'sv' => $sv));
            if ($isMember) {
                $canUpdate = true;
                break;
            }
        }
        $multiMail = ModUtil::getVar('IWmessages', 'multiMail');

        //Check if the user can really send multiple mails to the grups especified
        $canMultiMail = false;
        //Get the group of the user who send the message
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        $userGroups = ModUtil::func('IWmain', 'user', 'getAllUserGroups',
                        array('uid' => UserUtil::getVar('uid'),
                            'sv' => $sv));
        foreach ($userGroups as $userGroup) {
            $multip = explode('|', $multi);
            if (strpos($multiMail, '$' . $userGroup['id'] . '|0-0|0$') != 0 ||
                    strpos($multiMail, '$' . $userGroup['id'] . '|0-' . $multi . '$') != 0 ||
                    strpos($multiMail, '$' . $userGroup['id'] . '|0-' . $multip[0] . '|0$') != 0) {
                //The user can send to everybody
                $canMultiMail = true;
                break;
            }
        }
        //Add the user in the array of user who send the message
        if ($canMultiMail) {
            if ($multi == '0|0') {
                $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                $allUsers = ModUtil::func('IWmain', 'user', 'getAllUsersInfo',
                                array('sv' => $sv));
                foreach ($allUsers as $user) {
                    $usersId[] = UserUtil::getIdFromName($user);
                }
            } else {
                if ($multi != '0') {
                    $members = explode('|', $multi);
                    if ($members[1] == 0) {
                        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                        $membersList = ModUtil::func('IWmain', 'user', 'getMembersGroup',
                                        array('sv' => $sv,
                                            'gid' => $members[0]));
                    } else {
                        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                        $membersList = ModUtil::func('IWmain', 'user', 'getMembersGroup',
                                        array('sv' => $sv,
                                            'gid' => $members[1]));
                    }
                    foreach ($membersList as $member) {
                        $usersId[] = $member['id'];
                    }
                }
            }
        }

        if (count($usersId) == 0) {
            LogUtil::registerError(_MESSAGESUSERNOTINDB . ', ' . $this->__('Please check that the name of the user you are sending a message to is a real user and known by this system.'));
        } else {
            if ($canUpdate) {
                //Update the attached files to the server
                for ($i = 1; $i < 4; $i++) {
                    $update = array();
                    $file = 'file' . $i;
                    $$file = str_replace(' ', '_', $_FILES['file' . $i]['name']);
                    if ($$file != '') {
                        $folder = ModUtil::getVar('IWmessages', 'uploadFolder');
                        $fileName = md5($$file . UserUtil::getVar('uid'));
                        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                        $update = ModUtil::func('IWmain', 'user', 'updateFile',
                                        array('sv' => $sv,
                                            'folder' => $folder,
                                            'fileNameTemp' => $_FILES['file' . $i]['tmp_name'],
                                            'fileRealName' => $_FILES['file' . $i]['name'],
                                            'fileSize' => $_FILES['file' . $i]['size'],
                                            'fileName' => $fileName));
                        //the function returns the error string if the update fails and empty string if success
                        if ($update['msg'] != '') {
                            LogUtil::registerError($update['msg'] . ' ' . $this->__('Probably the message has been sent without the attached file'));
                            $$file = '';
                        }
                    }
                }
            } else {
                $file1 = '';
                $file2 = '';
                $file3 = '';
            }

            foreach ($usersId as $userId) {
                if (ModUtil::apiFunc('IWmessages', 'user', 'create',
                                array('image' => $image,
                                    'subject' => $subject,
                                    'to_userid' => $userId,
                                    'message' => $message,
                                    'reply' => $reply,
                                    'file1' => str_replace(' ', '_', $file1),
                                    'file2' => str_replace(' ', '_', $file2),
                                    'file3' => str_replace(' ', '_', $file3)))) {
                    $this->view->clear_cache(null, $to_userid);
                    $sended++;
                } else {
                    $error++;
                }
            }
        }
        if ($sended > 0) {
            $sendedText = ($sended > 1) ? $this->__('Number of sent messages:') . ' ' . $sended : '';
            LogUtil::registerStatus($this->__('Your message has been posted.') . ' ' . $sendedText);
            if ($replied > 0) {
                //Set a message as replied
                ModUtil::apiFunc('IWmessages', 'user', 'setreplied',
                                array('msgid' => $replied));
            }
        }
        if ($error > 0) {
            $errorText = ($error > 1) ? $this->__('Errors number:') . ' ' . $error : '';
            LogUtil::registerError($this->__('Error! Creation attempt failed.') . ' ' . $errorText);
        }
        return System::redirect((UserUtil::isLoggedIn()) ? ModUtil::url('IWmessages', 'user', 'view') : 'index.php');
    }
Esempio n. 11
0
 /**
  * Returns an TimeIt_Filter_OperatorIf instance form an expression.
  *
  * @param string $objectType Object type.
  * @param string $exp        Expression in format: field:operator:value .
  * 
  * @return TimeIt_Filter_OperatorIf
  * @throws InvalidArgumentException In case of invalid parameters.
  * @throws LogicException If operation class does not extend this class.
  */
 public static function operatorFromExp($objectType, $exp)
 {
     $pattern = '/^([0-9a-zA-Z_-]+):([0-9a-zA-Z_-]+):(.*)$/';
     // extract parts
     if (preg_match_all($pattern, $exp, $array)) {
         $field = $array[1][0];
         $operator = $array[2][0];
         $value = $array[3][0];
         if (strlen($value) > 0) {
             // check field
             $class = 'TimeIt_Filter_OP_' . DataUtil::formatForOS($operator);
             // check operator
             if (class_exists($class)) {
                 $rfclass = new ReflectionClass($class);
                 // check operator class (need to use reflection because we can't create an instance yet)
                 if ($rfclass->isSubclassOf(new ReflectionClass('TimeIt_Filter_OP_Interface'))) {
                     if (($field == 'cr_uid' || $field == 'lu_uid') && (int) $value == -1) {
                         $value = UserUtil::getVar('uid', -1, 1);
                         // set uid of current user
                     } else {
                         if (($field == 'cr_uid' || $field == 'lu_uid') && !preg_match('/^[0-9]+$/', $value)) {
                             if ($value == 'User Name') {
                                 return null;
                             } else {
                                 $name = $value;
                                 $value = $uid = UserUtil::getIdFromName($value);
                                 // get user id form user name
                                 if (empty($uid)) {
                                     // show error
                                     LogUtil::registerError(__f('The user named "%s" not found (TimeIt filter).', $name, ZLanguage::getModuleDomain('TimeIt')));
                                     return null;
                                 }
                             }
                         } else {
                             if (($field == 'cr_uid' || $field == 'up_uid') && preg_match('/^[0-9]+$/', $value)) {
                                 $value = (int) $value;
                             }
                         }
                     }
                     if ($value) {
                         return new $class($objectType, $field, $value);
                     } else {
                         return null;
                     }
                 } else {
                     throw new LogicException('Class of operator ' . $operator . ' (' . $class . ') is not a subclass of TimeIt_Filter_OP_Interface.');
                 }
             } else {
                 throw new InvalidArgumentException('Expression has got an invalid operator (' . $operator . ').');
             }
         }
         // ignore filter
     } else {
         throw new InvalidArgumentException('Expression has got an invalid format.');
     }
 }
Esempio n. 12
0
    /**
     * Display the block.
     *
     * @param array $blockinfo A blockinfo structure.
     * 
     * @return string The rendered block.
     */
    public function display($blockinfo)
    {
        // Check if the Profile module is available.
        if (!ModUtil::available('Profile')) {
            return false;
        }

        // Security check
        if (!SecurityUtil::checkPermission('Profile:FeaturedUserblock:', "$blockinfo[bid]::", ACCESS_READ)) {
            return false;
        }

        // Get variables from content block
        $vars = BlockUtil::varsFromContent($blockinfo['content']);

        // If there's no user to show, nothing to do
        if (!isset($vars['username']) || empty($vars['username'])) {
            return false;
        }

        // Defaults
        if (!isset($vars['fieldstoshow']) || !is_array($vars['fieldstoshow']) || empty($vars['fieldstoshow'])) {
            $vars['fieldstoshow'] = array();
        }

        if (!isset($vars['showregdate']) || empty($vars['showregdate'])) {
            $vars['showregdate'] = '';
        }

        $userinfo = UserUtil::getVars(UserUtil::getIdFromName($vars['username']));

        // Check if the user is watching its own profile or if he is admin
        $currentuser = UserUtil::getVar('uid');
        $ismember    = ($currentuser >= 2);
        $sameuser    = ($currentuser == $userinfo['uid']);

        $isadmin     = false;
        if (SecurityUtil::checkPermission('Profile::', '::', ACCESS_ADMIN)) {
            $isadmin = true;
        }

        // get all active profile fields
        $activeduds = ModUtil::apiFunc('Profile', 'user', 'getallactive', array('index' => 'prop_label'));

        foreach ($activeduds as $dudlabel => $activedud) {
            // check if the attribute is set to be shown in the block
            if (!in_array($activedud['prop_attribute_name'], $vars['fieldstoshow'])) {
                continue;
            }

            // discard empty fields
            if (empty($userinfo['__ATTRIBUTES__'][$activedud['prop_attribute_name']])) {
                continue;
            }

            // check the access to this field
            if ($activedud['prop_viewby'] != 0) {
                // not to everyone, checks members only or higher
                if (!($activedud['prop_viewby'] == 1 && $ismember)) {
                    // lastly check for the same user or admin
                    if (!($activedud['prop_viewby'] == 2 && ($sameuser || $isadmin))) {
                        continue;
                    }
                }
            }

            // add it to the viewable properties
            $dudarray[$dudlabel] = $userinfo['__ATTRIBUTES__'][$activedud['prop_attribute_name']];
        }
        unset($activeduds);

        // build the output
        $this->view->setCacheId('featured'.$vars['username']);

        $this->view->assign('userinfo',    $userinfo);
        $this->view->assign('showregdate', $vars['showregdate']);
        $this->view->assign('dudarray',    $dudarray);

        $blockinfo['content'] = $this->view->fetch('profile_block_featureduser.tpl');

        return BlockUtil::themeBlock($blockinfo);
    }
Esempio n. 13
0
    /**
     * Display item.
     * 
     * Parameters passed via the $args array, or via GET:
     * --------------------------------------------------
     * numeric uid   The user account id (uid) of the user for whom to display profile information; optional, ignored if uname is supplied, if not provided 
     *                  and if uname is not supplied then defaults to the current user.
     * string  uname The user name of the user for whom to display profile information; optional, if not supplied, then uid is used to determine the user.
     * string  page  The name of the Profile "page" (view template) to display; optional, if not provided then the standard view template is used.
     * 
     * @param array $args All parameters passed to this function via an internal call.
     *
     * @return string The rendered template output.
     */
    public function view($args)
    {
        // Security check
        if (!SecurityUtil::checkPermission('Profile::view', '::', ACCESS_READ)) {
            return LogUtil::registerPermissionError();
        }

        // Get parameters from whatever input we need.
        $uid   = (int)$this->request->getGet()->get('uid', isset($args['uid']) ? $args['uid'] : null);
        $uname = $this->request->getGet()->get('uname', isset($args['uname']) ? $args['uname'] : null);
        $page  = $this->request->getGet()->get('page', isset($args['page']) ? $args['page'] : null);

        // Getting uid by uname
        if (!empty($uname)) {
            $uid = UserUtil::getIdFromName($uname);
        } elseif (empty($uid)) {
            $uid = UserUtil::getVar('uid');
        }

        // Check for an invalid uid (uid = 1 is the anonymous user)
        if ($uid < 2) {
            return LogUtil::registerError($this->__('Error! Could not find this user.'), 404);
        }

        // Get all the user data
        $userinfo = UserUtil::getVars($uid);

        if (!$userinfo) {
            return LogUtil::registerError($this->__('Error! Could not find this user.'), 404);
        }

        // Check if the user is watching its own profile or if he is admin
        // TODO maybe remove the four lines below
        $currentuser = UserUtil::getVar('uid');
        $ismember    = ($currentuser >= 2);
        $isowner     = ($currentuser == $uid);
        $isadmin     = SecurityUtil::checkPermission('Profile::', '::', ACCESS_ADMIN);

        // Get all active profile fields
        $activeduds = ModUtil::apiFunc('Profile', 'user', 'getallactive',
                array('get' => 'viewable',
                'uid' => $uid));

        // Fill the DUD values array
        $dudarray = array();
        foreach (array_keys($activeduds) as $dudattr) {
            $dudarray[$dudattr] = isset($userinfo['__ATTRIBUTES__'][$dudattr]) ? $userinfo['__ATTRIBUTES__'][$dudattr] : '';
        }

        // Create output object
        $this->view->setCaching(false)->add_core_data();

        $this->view->assign('dudarray', $dudarray)
            ->assign('fields',   $activeduds)
            ->assign('uid',      $userinfo['uid'])
            ->assign('uname',    $userinfo['uname'])
            ->assign('userinfo', $userinfo)
            ->assign('ismember', $ismember)
            ->assign('isadmin',  $isadmin)
            ->assign('sameuser', $isowner);

        // Return the output that has been generated by this function
        if (!empty($page)) {
            if ($this->view->template_exists("profile_user_view_{$page}.tpl")) {
                return $this->view->fetch("profile_user_view_{$page}.tpl", $uid);
            } else {
                return LogUtil::registerError($this->__f('Error! Could not find profile page [%s].', DataUtil::formatForDisplay($page)), 404);
            }
        }

        return $this->view->fetch('profile_user_view.tpl', $uid);
    }
Esempio n. 14
0
    /**
     * Display a form to confirm the deletion of one user, and then process the deletion.
     *
     * Parameters passed via GET:
     * --------------------------
     * numeric userid The user id of the user to be deleted.
     * string  uname  The user name of the user to be deleted.
     *
     * Parameters passed via POST:
     * ---------------------------
     * array   userid         The array of user ids of the users to be deleted.
     * boolean process_delete True to process the posted userid list, and delete the corresponding accounts; false or null to confirm first.
     *
     * Parameters passed via SESSION:
     * ------------------------------
     * None.
     *
     * @return string HTML string containing the rendered template.
     *
     * @throws Zikula_Exception_Forbidden Thrown if the current user does not have delete access, or if the method of accessing this function is improper.
     */
        
    public function deleteUsers()
    {
        // check permissions
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_DELETE));

        $proceedToForm = false;
        $processDelete = false;

        if ($this->request->isPost()) {
            $userid = $this->request->request->get('userId', null);
            $processDelete = $this->request->request->get('process_delete', false);            
            $proceedToForm = !$processDelete;            
        } elseif ($this->request->isGet()) {
            $userid = $this->request->query->get('uid', null);
            $uname  = $this->request->query->get('uname', null);

            // retreive userid from uname
            if (empty($userid) && !empty($uname)) {
                $userid = UserUtil::getIdFromName($users);
            }

            $proceedToForm = true;
        } else {
            throw new Zikula_Exception_Forbidden();
        }

        if (empty($userid)) {            
            $this->registerError($this->__('No users have chosen'));
            $proceedToForm = false;
            $userid = array();
        } elseif (!is_array($userid)) {
            $userid = array($userid);
        } 
                    
        $currentUser = UserUtil::getVar('uid');
        $users = array();  
        foreach ($userid as $key => $uid) {
            if ($uid == 1) {
                $this->registerError($this->__("Error! You can't delete the guest account."));
                $proceedToForm = false;
                $processDelete = false;
            } elseif ($uid == 2) {
                $this->registerError($this->__("Error! You can't delete the primary administrator account."));
                $proceedToForm = false;
                $processDelete = false;
            } elseif ($uid == $currentUser) {
                $this->registerError($this->__("Error! You can't delete the account you are currently logged into."));
                $proceedToForm = false;
                $processDelete = false;
            }

            // get the user vars
            $users[$key] = UserUtil::getVars($uid);

            if (empty($users[$key])) {
                $this->registerError($this->__('Sorry! No such user found.'));
                $proceedToForm = false;
                $processDelete = false;
            }
        }

        if ($processDelete) {      
            $this->checkCsrfToken();
            $valid = true;
            foreach ($userid as $uid) {
                $event = new Zikula_Event('module.users.ui.validate_delete', null, array('id' => $uid), new Zikula_Hook_ValidationProviders());
                $validators = $this->eventManager->notify($event)->getData();

                $hook = new Zikula_ValidationHook('users.ui_hooks.user.validate_delete', $validators);
                $this->notifyHooks($hook);
                $validators = $hook->getValidators();

                if ($validators->hasErrors()) {
                    $valid = false;
                }
            }

            $proceedToForm = false;
            if ($valid) {
                $deleted = ModUtil::apiFunc($this->name, 'admin', 'deleteUser', array('uid' => $userid));

                if ($deleted) {
                    foreach ($userid as $uid) {
                        $event = new Zikula_Event('module.users.ui.process_delete', null, array('id' => $uid));
                        $this->eventManager->notify($event);

                        $hook = new Zikula_ProcessHook('users.ui_hooks.user.process_delete', $uid);
                        $this->notifyHooks($hook);
                    }
                    $count = count($userid);
                    $this->registerStatus($this->_fn('Done! Deleted %1$d user account.', 'Done! Deleted %1$d user accounts.', $count, array($count)));
                }
            }
        }

        if ($proceedToForm) {
            return $this->view->assign('users', $users)
                ->fetch('IWusers_admin_deleteusers.tpl');
        } else {
            $this->redirect(ModUtil::url($this->name, 'admin', 'main'));
        }
    }
/**
 * Smarty function to display user links for the Profile module
 *
 * Example
 * {profileuserlinks start='' end='' seperator='|' class='z-menuitem-title'}
 *
 * Parameters passed in via the $params array:
 * -------------------------------------------
 * string start     Start string.
 * string end       End string.
 * string seperator Link seperator.
 * string class     CSS class.
 * string default   Default content if there are no links to show (default: <hr />).
 * 
 * @param array  $params  All attributes passed to this function from the template.
 * @param object &$smarty Reference to the Zikula_View/Smarty object.
 * 
 * @return string|boolean The results of the module function; empty string if the Profile module is not available; false if error.
 */
function smarty_function_profileuserlinks($params, &$smarty)
{
    // set some defaults
    if (!isset($params['start'])) {
        $params['start'] = '[';
    }
    if (!isset($params['end'])) {
        $params['end'] = ']';
    }
    if (!isset($params['seperator'])) {
        $params['seperator'] = '|';
    }
    if (!isset($params['class'])) {
        $params['class'] = 'z-menuitem-title';
    }
    if (!isset($params['default'])) {
        $params['default'] = '<hr />';
    }

    if (!UserUtil::isLoggedIn()) {
        return $params['default'];
    }

    $dom = ZLanguage::getModuleDomain('Profile');

    $func = FormUtil::getPassedValue('func', 'main', 'GET');
    
    $currentfunc = (isset($func) && !empty($func)) ? $func : 'main';

    $currentuser  = UserUtil::getVar('uid');
    $currentuname = UserUtil::getVar('uname');

    $userlinks  = '';
    $linksarray = array();

    // process the memberlist functions first
    if (in_array($currentfunc, array('viewmembers', 'recentmembers', 'onlinemembers'))) {
        $userlinks = "<div class=\"z-menu\">\n";
        $userlinks .= "<span class=\"$params[class]\">$params[start] ";

        if ($currentuser >= 2) {
            $linksarray[] = '<a href="' . ModUtil::url('Users', 'user', 'main') . '">' . __('User account panel', $dom) . '</a>';
        }
        if ($currentfunc != 'viewmembers') {
            $linksarray[] = '<a href="' . ModUtil::url('Profile', 'user', 'viewmembers') . '">' . __('Registered users list', $dom) . '</a>';
        }
        if ($currentfunc != 'recentmembers') {
            $linksarray[] = '<a href="' . ModUtil::url('Profile', 'user', 'recentmembers') . '">' . __f('Last %s registered users', ModUtil::getVar('Profile', 'recentmembersitemsperpage'), $dom) . '</a>';
        }
        if ($currentfunc != 'onlinemembers') {
            $linksarray[] = '<a href="' . ModUtil::url('Profile', 'user', 'onlinemembers') . '">' . __('Users currently on-line', $dom) . '</a>';
        }

        $userlinks .= implode(" $params[seperator] ", $linksarray);
        $userlinks .= $params['end'] . "</span>\n";
        $userlinks .= "</div>\n";
        
        return $userlinks;
    }

    // default values for essential vars
    if (!isset($smarty->_tpl_vars['ismember'])) {
        $smarty->_tpl_vars['ismember'] = ($currentuser >= 2);
    }
    if (!isset($smarty->_tpl_vars['sameuser'])) {
        if (isset($smarty->_tpl_vars['uid'])) {
            $smarty->_tpl_vars['sameuser'] = ($currentuser == $smarty->_tpl_vars['uid']);
            $smarty->_tpl_vars['uname'] = UserUtil::getVar('uname', $smarty->_tpl_vars['uid']);
        } elseif (isset($smarty->_tpl_vars['uname'])) {
            $smarty->_tpl_vars['sameuser'] = ($currentuname == $smarty->_tpl_vars['uname']);
            $smarty->_tpl_vars['uid'] = UserUtil::getIdFromName($smarty->_tpl_vars['uname']);
        } else {
            $smarty->_tpl_vars['sameuser'] = false;
        }
    }

    // process the common functions
    if ($smarty->_tpl_vars['ismember'] && $smarty->_tpl_vars['sameuser']) {
        $linksarray[] = '<a href="' . ModUtil::url('Users', 'user', 'main') . '">' . __('User account panel', $dom) . '</a>';
    }

    if ($smarty->_tpl_vars['sameuser'] && $currentfunc != 'modify') {
        $linksarray[] = '<a href="' . ModUtil::url('Profile', 'user', 'modify') . '">' . __('Edit personal info', $dom) . '</a>';
    }

    if ($smarty->_tpl_vars['ismember'] && $currentfunc != 'view') {
        $linksarray[] = '<a href="' . ModUtil::url('Profile', 'user', 'view', array('uid' => $currentuser)) . '">' . __('View personal info', $dom) . '</a>';
    }

    if (!$smarty->_tpl_vars['sameuser']) {
        // check for the messaging module
        $msgmodule = System::getVar('messagemodule');
        if (isset($smarty->_tpl_vars['uid']) && ModUtil::available($msgmodule)) {
            $linksarray[] = '<a href="' . ModUtil::url($msgmodule, 'user', 'newpm', array('uid' => $smarty->_tpl_vars['uid'])) . '">' . __('Send private message', $dom) . '</a>';
        }
    }
        
    // build the z-menu if there's an option
    if (!empty($linksarray)) {
        $userlinks = "<div class=\"z-menu\">\n";
        $userlinks .= "<span class=\"$params[class]\">$params[start] ";
        $userlinks .= implode(" $params[seperator] ", $linksarray);
        $userlinks .= $params['end'] . "</span>\n";
        $userlinks .= "</div>\n";
    }

    // ContactList integration
    if (!$smarty->_tpl_vars['sameuser'] && ModUtil::available('ContactList')) {
        $buddystatus = ModUtil::apiFunc('ContactList', 'user', 'isBuddy', array('uid1' => $currentuser, 'uid2' => $smarty->_tpl_vars['uid']));

        $linksarray = array(); 

        if (empty($userlinks)) {
            $linksarray[] = '<a href="' . ModUtil::url('Users', 'user', 'main') . '">' . __('User account panel', $dom) . '</a>';
        }
        $linksarray[] = '<a href="' . ModUtil::url('ContactList', 'user', 'display', array('uid' => $smarty->_tpl_vars['uid'])) . '">' . __f('Show %s\'s contacts', $smarty->_tpl_vars['uname'], $dom) . '</a>';
        if ($buddystatus) {
            $linksarray[] = '<a href="' . ModUtil::url('ContactList', 'user', 'edit', array('id' => $buddystatus)) . '">' . __('Edit contact', $dom) . '</a>';
        } else {
            $linksarray[] = '<a href="' . ModUtil::url('ContactList', 'user', 'create', array('uid' => $smarty->_tpl_vars['uid'])) . '">' . __('Add as contact', $dom) . '</a>';
        }

        $userlinks .= "<div class=\"z-menu\">\n";
        $userlinks .= "<span class=\"$params[class]\">$params[start] ";
        $userlinks .= implode(" $params[seperator] ", $linksarray);
        $userlinks .= $params['end'] . "</span></div>\n";
    }

    return !empty($userlinks) ? $userlinks : $params['default'];
}
Esempio n. 16
0
    public function viewStats($args) {
        $statsSaved = unserialize(SessionUtil::getVar('statsSaved'));

        $moduleName = (isset($statsSaved['moduleName'])) ? $statsSaved['moduleName'] : '';
        $fromDate = (isset($statsSaved['fromDate'])) ? $statsSaved['fromDate'] : null;
        $toDate = (isset($statsSaved['toDate'])) ? $statsSaved['toDate'] : '';

        $moduleName = FormUtil::getPassedValue('moduleName', isset($args['moduleName']) ? $args['moduleName'] : $moduleName, 'GETPOST');
        $uname = FormUtil::getPassedValue('uname', isset($args['uname']) ? $args['uname'] : $statsSaved['uname'], 'GETPOST');
        $fromDate = FormUtil::getPassedValue('fromDate', isset($args['fromDate']) ? $args['fromDate'] : $fromDate, 'GETPOST');
        $toDate = FormUtil::getPassedValue('toDate', isset($args['toDate']) ? $args['toDate'] : $toDate, 'GETPOST');
        $uid = FormUtil::getPassedValue('uid', isset($args['uid']) ? $args['uid'] : 0, 'GETPOST');

        if ($uid > 0) {
            $uname = UserUtil::getVar('uname', $uid);
        }

        SessionUtil::setVar('statsSaved', serialize(array('uname' => $uname,
                    'moduleName' => $moduleName,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                )));


        if (!SecurityUtil::checkPermission('IWstats::', '::', ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        $uid = 0;
        $rpp = 50;
        $lastDays = 10;
        $nusers = 0;

        if ($uname != null && $uname != '') {
            // get user id from uname
            $uid = UserUtil::getIdFromName($uname);
            if (!$uid) {
                LogUtil::registerError(__f('User \'%s\' not found', array($uname)));
                $uname = '';
            }
        }

        $time = time();

        if ($fromDate != null) {
            $fromDate = mktime(0, 0, 0, substr($fromDate, 3, 2), substr($fromDate, 0, 2), substr($fromDate, 6, 4));
            $fromDate = date('Y-m-d 00:00:00', $fromDate);
            $fromDate = DateUtil::makeTimestamp($fromDate);
            $fromDate = date('d-m-Y', $fromDate);
        } else {
            $fromDate = date('d-m-Y', $time - $lastDays * 24 * 60 * 60);
        }

        if ($toDate != null) {
            $toDate = mktime(0, 0, 0, substr($toDate, 3, 2), substr($toDate, 0, 2), substr($toDate, 6, 4));
            $toDate = date('Y-m-d 00:00:00', $toDate);
            $toDate = DateUtil::makeTimestamp($toDate);
            $toDate = date('d-m-Y', $toDate);
        } else {
            $toDate = date('d-m-Y', $time);
        }

        // get last records
        $records = ModUtil::apiFunc('IWstats', 'user', 'getAllSummary', array('rpp' => -1,
                    'init' => -1,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                ));

        // get all modules
        $modules = ModUtil::apiFunc('Extensions', 'admin', 'listmodules', array('state' => 0));

        foreach ($modules as $module) {
            $modulesNames[$module['id']] = $module['name'];
            $modulesArray[] = array('id' => $module['id'],
                'name' => $module['name']);
        }

        $modulesNames[0] = $this->__('unknown');

        $usersListArray = array();
        $moduleStatsArray = array();
        $userModulesArray = array();
        $userArray = array();
        $moduleArray = array();
        $usersForModule = array();
        $users = array();
        $usersIpCounter = 0;
        $nRecords = 0;
        $userNRecords = 0;
        $usersList = '';
        $userName = '';
        foreach ($records as $record) {
            $nRecords = $nRecords + $record['nrecords'];
            $usersIpCounter = $usersIpCounter + $record['nips'];
            $users = explode('$$', substr($record['users'], 1, -1)); // substr to remove $ in the begining and the end of the string
            foreach ($users as $user) {
                $oneUser = explode('|', $user);

                if (!in_array($oneUser[0], $usersListArray)) {
                    $nusers++;
                    $usersListArray[] = $oneUser[0];
                }
                if ($oneUser[0] == $uid && $uid > 0) {
                    $userInit = '$' . $uid . '|';
                    $userDataPos = strpos($record['users'], $userInit);
                    $subDataPre = substr($record['users'], $userDataPos + strlen($userInit));
                    $userDataPos = strpos($subDataPre, '$');
                    $subDataPre = substr($subDataPre, 0, $userDataPos);
                    $userModules = explode('#', $subDataPre);
                    foreach ($userModules as $module) {
                        $oneModule = explode('=', $module);
                        if (array_key_exists($modulesNames[$oneModule[0]], $userModulesArray)) {
                            $userModulesArray[$modulesNames[$oneModule[0]]] = $oneModule[1];
                        } else {
                            $userModulesArray[$modulesNames[$oneModule[0]]] = $userModulesArray[$modulesNames[$oneModule[0]]] + $oneModule[1];
                        }

                        $userNRecords = $userNRecords + $oneModule[1];
                    }
                }
                if ($moduleName != '') {
                    $moduleId = ModUtil::getIdFromName($moduleName);
                    if ((strpos($oneUser[1], $moduleId . '=') !== false && strpos($oneUser[1], $moduleId . '=') == 0) || strpos($oneUser[1], '#' . $moduleId . '=') !== false) {
                        // get the number of views
                        $pos = strpos($oneUser[1], $moduleId . '=');
                        if ($pos != 0) {
                            $pos = strpos($oneUser[1], '#' . $moduleId . '=');
                        }
                        $preString = substr($oneUser[1], $pos);
                        //print $preString . '<br />';
                        if ($pos != 0) {
                            $preString = substr($preString, 1);
                        }
                        $pos = strpos($preString, '#');
                        $preString = ($pos == 0) ? $preString : substr($preString, 0, $pos);
                        $num = explode('=', $preString);
                        if (!array_key_exists($oneUser[0], $usersForModule)) {
                            $usersForModule[$oneUser[0]] = $num[1];
                            $usersList .= $oneUser[0] . '$$';
                        } else {
                            $usersForModule[$oneUser[0]] = $usersForModule[$oneUser[0]] + $num[1];
                        }
                    }
                }
            }

            $modules = explode('$$', substr($record['modules'], 1, -1)); // substr to remove $ in the begining and the end of the string
            foreach ($modules as $module) {
                $oneModule = explode('|', $module);
                if (isset($modulesNames[$oneModule[0]])) {
                    if (!array_key_exists($modulesNames[$oneModule[0]], $moduleStatsArray)) {
                        $moduleStatsArray[$modulesNames[$oneModule[0]]] = $oneModule[1];
                    } else {
                        $moduleStatsArray[$modulesNames[$oneModule[0]]] = $moduleStatsArray[$modulesNames[$oneModule[0]]] + $oneModule[1];
                    }
                }
            }
        }

        ksort($userModulesArray);

        if ($uid > 0) {
            $userArray = array('nRecords' => $userNRecords,
                'userModulesArray' => $userModulesArray,
            );
        }

        ksort($moduleStatsArray);

        if ($uid > 0) {
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $userName = ModUtil::func('IWmain', 'user', 'getUserInfo', array('info' => 'ncc',
                        'sv' => $sv,
                        'uid' => $uid));
        }

        if ($moduleName != '') {
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $users = ModUtil::func('IWmain', 'user', 'getAllUsersInfo', array('info' => 'ncc',
                        'sv' => $sv,
                        'list' => $usersList,
                    ));
            $users[0] = $this->__('Unregistered');
        }

        return $this->view->assign('users', $users)
                        ->assign('nRecords', $nRecords)
                        ->assign('nusers', $nusers)
                        ->assign('userName', $userName)
                        ->assign('usersIpCounter', $usersIpCounter)
                        ->assign('modulesNames', $modulesNames)
                        ->assign('modulesArray', $modulesArray)
                        ->assign('moduleName', $moduleName)
                        ->assign('uname', $uname)
                        ->assign('fromDate', $fromDate)
                        ->assign('toDate', $toDate)
                        ->assign('userArray', $userArray)
                        ->assign('maxDate', date('Ymd', time()))
                        ->assign('usersForModule', $usersForModule)
                        ->assign('moduleStatsArray', $moduleStatsArray)
                        ->fetch('IWstats_admin_stats.htm');
    }
Esempio n. 17
0
    /**
     * view permissions
     * @return string HTML string
     */
    public function view()
    {
        // Security check
        if (!SecurityUtil::checkPermission('Permissions::', '::', ACCESS_ADMIN)) {
            return LogUtil::registerPermissionError();
        }

        // Get parameters from whatever input we need.
        $permgrp = FormUtil::getPassedValue('permgrp', -1, 'REQUEST');
        $testuser = FormUtil::getPassedValue('test_user', null, 'POST');
        $testcomponent = FormUtil::getPassedValue('test_component', null, 'POST');
        $testinstance = FormUtil::getPassedValue('test_instance', null, 'POST');
        $testlevel = FormUtil::getPassedValue('test_level', null, 'POST');

        $testresult = '';
        if (!empty($testuser) &&
                !empty($testcomponent) &&
                !empty($testinstance)
        ) {
            // we have everything we need for an effective permission check
            $testuid = UserUtil::getIdFromName($testuser);
            if ($testuid <> false) {
                if (SecurityUtil::checkPermission($testcomponent, $testinstance, $testlevel, $testuid)) {
                    $testresult = '<span id="permissiontestinfogreen">' . $this->__('permission granted.') . '</span>';
                } else {
                    $testresult = '<span id="permissiontestinfored">' . $this->__('permission not granted.') . '</span>';
                }
            } else {
                $testresult = '<span id="permissiontestinfored">' . $this->__('unknown user.') . '</span>';
            }
        }

        $this->view->assign('testuser', $testuser)
                ->assign('testcomponent', $testcomponent)
                ->assign('testinstance', $testinstance)
                ->assign('testlevel', $testlevel)
                ->assign('testresult', $testresult);

        // decide the default view
        $enableFilter = $this->getVar('filter', 1);
        $rowview = $this->getVar('rowview', 25);

        // Work out which tables to operate against, and
        // various other bits and pieces
        $dbtable = DBUtil::getTables();
        $permcolumn = $dbtable['group_perms_column'];
        $ids = $this->getGroupsInfo();

        $where = '';
        if ($enableFilter == 1) {
            $permgrpparts = explode('+', $permgrp);
            if ($permgrpparts[0] == 'g') {
                if (is_array($permgrpparts) && $permgrpparts[1] != SecurityUtil::PERMS_ALL) {
                    $where = "WHERE (" . $permcolumn['gid'] . "='" . SecurityUtil::PERMS_ALL . "' OR " . $permcolumn['gid'] . "='" . DataUtil::formatForStore($permgrpparts[1]) . "')";
                    $permgrp = $permgrpparts[1];
                    $this->view->assign('filtertype', 'group');
                } else {
                    $permgrp = SecurityUtil::PERMS_ALL;
                    $where = '';
                }
            } elseif ($permgrpparts[0] == 'c') {
                if (is_array($permgrpparts) && $permgrpparts[1] != SecurityUtil::PERMS_ALL) {
                    $where = "WHERE (" . $permcolumn['component'] . "='.*' OR " . $permcolumn['component'] . " LIKE '" . DataUtil::formatForStore($permgrpparts[1]) . "%')";
                    $permgrp = $permgrpparts[1];
                    $this->view->assign('filtertype', 'component');
                } else {
                    $permgrp = SecurityUtil::PERMS_ALL;
                    $where = '';
                }
            } else {
                $this->view->assign('filtertype', '');
            }
            $this->view->assign('permgrps', $ids);
            $this->view->assign('permgrp', $permgrp);
            $this->view->assign('enablefilter', true);
        } else {
            $this->view->assign('enablefilter', false);
            $this->view->assign('filtertype', '');
            $this->view->assign('permgrp', SecurityUtil::PERMS_ALL);
        }

        $accesslevels = SecurityUtil::accesslevelnames();

        $orderBy = "ORDER BY $permcolumn[sequence]";
        $objArray = DBUtil::selectObjectArray('group_perms', $where, $orderBy, -1, -1, false);
        $numrows = DBUtil::_getFetchedObjectCount();

        $permissions = array();
        $components = array(-1 => $this->__('All components'));
        if ($numrows > 0) {
            $csrftoken = SecurityUtil::generateCsrfToken($this->serviceManager, true);
            $rownum = 1;
            $ak = array_keys($objArray);
            foreach ($ak as $v) {
                $obj = $objArray[$v];
                $id = $obj['gid'];
                $up = array('url' => ModUtil::url('Permissions', 'admin', 'inc',
                                array('pid' => $obj['pid'],
                                        'permgrp' => $permgrp,
                                        'csrftoken' => $csrftoken)),
                        'title' => $this->__('Up'));
                $down = array('url' => ModUtil::url('Permissions', 'admin', 'dec',
                                array('pid' => $obj['pid'],
                                        'permgrp' => $permgrp,
                                        'csrftoken' => $csrftoken)),
                        'title' => $this->__('Down'));
                switch ($rownum) {
                    case 1:
                        $arrows = array('up' => 0, 'down' => 1);
                        break;
                    case $numrows:
                        $arrows = array('up' => 1, 'down' => 0);
                        break;
                    default:
                        $arrows = array('up' => 1, 'down' => 1);
                        break;
                }
                $rownum++;

                $options = array();
                $inserturl = ModUtil::url('Permissions', 'admin', 'listedit',
                                array('permgrp' => $permgrp,
                                        'action' => 'insert',
                                        'insseq' => $obj['sequence']));
                $editurl = ModUtil::url('Permissions', 'admin', 'listedit',
                                array('chgpid' => $obj['pid'],
                                        'permgrp' => $permgrp,
                                        'action' => 'modify'));
                $deleteurl = ModUtil::url('Permissions', 'admin', 'delete',
                                array('pid' => $obj['pid'],
                                        'permgrp' => $permgrp));

                $permissions[] = array('sequence' => $obj['sequence'],
                        'arrows' => $arrows,
                        // Realms not currently functional so hide the output - jgm
                        //'realms'    => $realms[$realm],
                        'group' => $ids[$id],
                        'groupid' => $id,
                        'component' => $obj['component'],
                        'instance' => $obj['instance'],
                        'accesslevel' => $accesslevels[$obj['level']],
                        'accesslevelid' => $obj['level'],
                        'options' => $options,
                        'up' => $up,
                        'down' => $down,
                        'permid' => $obj['pid'],
                        'inserturl' => $inserturl,
                        'editurl' => $editurl,
                        'deleteurl' => $deleteurl);
            }
        }

        // read all perms to extract components
        $allPerms = DBUtil::selectObjectArray('group_perms', '', $orderBy, -1, -1, false);
        foreach ($allPerms as $singlePerm) {
            // extract components, we keep everything up to the first colon
            $compparts = explode(':', $singlePerm['component']);
            $components[$compparts[0]] = $compparts[0];
        }

        $this->view->assign('groups', $this->getGroupsInfo());
        $this->view->assign('permissions', $permissions);
        $this->view->assign('components', $components);

        $lockadmin = ($this->getVar('lockadmin')) ? 1 : 0;
        $this->view->assign('lockadmin', $lockadmin);
        $this->view->assign('adminid', $this->getVar('adminid'));

        // Assign the permission levels
        $this->view->assign('permissionlevels', SecurityUtil::accesslevelnames());

        return $this->view->fetch('permissions_admin_view.tpl');
    }
Esempio n. 18
0
    /**
     * When Zikula authentication has failed, start SiriusXtecAuth
     * 
     * @return bool true authetication succesful
     */
    public static function trySiriusXtecAuth(Zikula_Event $event)
    {
        $authentication_info = FormUtil::getPassedValue('authentication_info', isset($args['authentication_info']) ? $args['authentication_info'] : null, 'POST');
        // Argument check
        if ($authentication_info['login_id'] == '' || $authentication_info['pass'] == '') {
            LogUtil::registerError(__('Usuari o contrasenya en blanc.'));
            return System::redirect(System::getHomepageUrl());
        }

        $uname = $authentication_info['login_id'];
        $pass = $authentication_info['pass'];

        // check if ldap is active
        if (!ModUtil::getVar('SiriusXtecAuth','ldap_active',false)) return false;
        // checking new users case
        $userid = UserUtil::getIdFromName($uname);
        if (($userid === false) && (ModUtil::getVar('SiriusXtecAuth','users_creation',false) === false)) return false;
        
        // connect to ldap server
        if (!$ldap_ds = ldap_connect(ModUtil::getVar('SiriusXtecAuth', 'ldap_server'))) {
            LogUtil::registerError(__('No ha pogut connectar amb el servidor ldap.'));
            return false;
        }        
        ///////////////////
        // Checking ldap validation
        $ldaprdn = ModUtil::getVar('SiriusXtecAuth', 'ldap_searchattr') . '=' . $uname . ',' . ModUtil::getVar('SiriusXtecAuth', 'ldap_basedn');
        $bind = @ldap_bind($ldap_ds, $ldaprdn, $pass);
        if (!$bind) {
            LogUtil::registerError(__('La informació introduïda no correspon a cap validació manual ni XTEC.'));
            return false;
        }
        LogUtil::getErrorMessages();
        // Case new users
        if ($userid === false) {
            $userLdapFields = array ('cn', 'uid', 'givenname', 'sn', 'mail');
            // search the directory for our user
            if (!$ldap_sr = ldap_search($ldap_ds, ModUtil::getVar('SiriusXtecAuth', 'ldap_basedn'), ModUtil::getVar('SiriusXtecAuth', 'ldap_searchattr') . '=' . DataUtil::formatForStore($uname),$userLdapFields)) {
                LogUtil::registerError(__('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (I).'));
                return false;
            }
            $info = ldap_get_entries($ldap_ds, $ldap_sr);
            if (!$info || $info['count'] == 0) {
                LogUtil::registerError('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (II).');
                return false;
            } else {
                if (!isset($info[0]['dn'])) {
                    LogUtil::registerError('Problemes en la creació d\'un nou usuari de Sirus des de la validació XTEC (III).');
                    return false;
                }
            }
            
            $user['zk']['uname'] =$uname;
            $user['zk']['email'] = $info[0]['mail'][0];
            if (ModUtil::getVar('SiriusXtecAuth','iw_write',false) && ModUtil::available('IWusers')) {
                $user['iw']['nom'] = ucwords(strtolower($info[0]['givenname'][0]));
                $cognom_separator = strpos($info[0]['sn'][0],' ');
                if ($cognom_separator && ModUtil::getVar('SiriusXtecAuth','iw_lastnames',false)) {
                    $user['iw']['cognom1'] = ucwords(strtolower(substr($info[0]['sn'][0],0,$cognom_separator)));
                    $user['iw']['cognom2'] = ucwords(strtolower(substr($info[0]['sn'][0],$cognom_separator+1)));
                } else{
                    $user['iw']['cognom1'] = ucwords(strtolower($info[0]['sn'][0]));
                    $user['iw']['cognom1'] = '';
                }
            }
            if (ModUtil::getVar('SiriusXtecAuth','new_users_activation', false)) {
                $user['zk']['activated'] = 1;
            }else {
                $user['zk']['activated'] = 0;
            }
            $user['gr'] = ModUtil::getVar('SiriusXtecAuth','new_users_groups');
            
            $userid = ModUtil::apifunc('SiriusXtecAuth', 'listeners', 'createUser', $user);
            if (!$userid) {
                LogUtil::registerError(__('No s\'ha pogut crear l\'usuari. Torneu a validar-vos.'));
                return false;
            }
            
        }
        
        @ldap_unbind($ldap_ds);
        UserUtil::setUserByUid($userid);
        
        if (!ModUtil::getVar('SiriusXtecAuth','loginXtecApps',false)) {
            return System::redirect(System::getHomepageUrl());
        } else {
			$pass_e = urlencode(base64_encode($pass));
            return System::redirect(ModUtil::url('SiriusXtecAuth', 'user', 'logingXtecApps',array('uname'=>$uname,'pass'=>$pass_e,'logtype'=>'in')));
        }

    }
Esempio n. 19
0
    /**
     * Retrieves the Zikula User ID (uid) for the given authenticationInfo, from the mapping maintained by this authenticationModule.
     *
     * Custom authenticationModules should pay extra special attention to the accurate association of authenticationInfo and user
     * ids (uids). Returning the wrong uid for a given authenticationInfo will potentially expose a user's account to
     * unauthorized access. Custom authenticationModules must also ensure that they keep their mapping table in sync with
     * the user's account.
     *
     * Note: (Specific to Zikula Users module authentication) This function uses mb_strtolower, and assumes that
     * locale == charset.
     *
     * Parameters passed in $args:
     * ---------------------------
     * array $args['authentication_info'] The information needed for this authenticationModule, including any user-entered
     *                                          information. For the Users module, this contains the elements 'login_id' and 'pass'.
     *                                          The 'login_id' element contains either the user name or the e-mail address of the
     *                                          user logging in, depending on the authentication_method. The 'pass' contains the
     *                                          password entered by the user.
     * array $args['authentication_method'] An array containing the authentication method, including the 'modname' (which should match this
     *                                          module's module name), and the 'method' method name. For the Users module, 'modname' would
     *                                          be 'Users' and 'method' would contain either 'email' or 'uname'.
     *
     * @param array $args All arguments passed to this function.
     *                      array   authenticationInfo  The authentication information uniquely associated with a user.
     *
     * @return integer|boolean The integer Zikula uid uniquely associated with the given authenticationInfo;
     *                          otherwise false if user not found or error.
     *
     * @throws Zikula_Exception_Fatal Thrown if invalid parameters are sent in $args.
     */
    public function getUidForAuthenticationInfo(array $args)
    {
        // authenticationInfo can contain anything necessary for the authentication method, but most of the time will contain
        // a login ID of some sort, and a password. Set up authenticationInfo in templates as name="authenticationInfo[fieldname]" to
        // gather what is needed. In this case, we don't care about any password that might be in authenticationInfo.

        $authenticatedUid = false;

        // Validate authenticationInfo
        if (!isset($args['authentication_info']) || !is_array($args['authentication_info'])
                || empty($args['authentication_info'])) {
            throw new Zikula_Exception_Fatal($this->__f('Invalid \'%1$s\' parameter provided in a call to %2$s.', array('authentication_info', __METHOD__)));
        }
        $authenticationInfo = $args['authentication_info'];

        if (!isset($args['authentication_method']) || !is_array($args['authentication_method'])
                || empty($args['authentication_method'])) {
            throw new Zikula_Exception_Fatal($this->__f('Invalid \'%1$s\' parameter provided in a call to %2$s.', array('authentication_method', __METHOD__)));
        }
        $authenticationMethod = $args['authentication_method'];

        // Custom authenticationModules can expect whatever they need in authentication_info. The authentication_method
        // parameter will contain the module name (which is a bit redundant) and the specific method name.

        $loginID = $authenticationInfo['login_id'];

        if (!isset($loginID) || (is_string($loginID) && empty($loginID))) {
            if ($authenticationMethod == 'email') {
                $detailedMessage = $this->__f('An e-mail address was not provided in a call to %1$s.', array(__METHOD__));
            } else {
                $detailedMessage = $this->__f('A user name was not provided in a call to %1$s.', array(__METHOD__));
            }
            throw new Zikula_Exception_Fatal($detailedMessage);
        } elseif (!is_string($loginID)) {
            throw new Zikula_Exception_Fatal($this->__f('Invalid type for \'%1$s\' parameter in a call to %2$s.', array('login_id', __METHOD__)));
        }

        // The users module expects the loginID to be lower case. Custom authenticationModules would do whatever
        // they needed here, if anything.
        $loginID = mb_strtolower($loginID);

        // Look up the authenticationInfo in the authentication-source to/from Zikula uid mapping table.
        //
        // Note: the following is a bad example for custom modules because there no mapping table for the Users module.
        // A custom authentication module would look up a uid using its own mapping tables, not the users table or UserUtil.
        if ($authenticationMethod['method'] == 'email') {
            $authenticatedUid = UserUtil::getIdFromEmail($loginID);
            if (!$authenticatedUid) {
                // Might be a registration. Acting as an authenticationModule, we should not care at this point about the user's
                // account status. The account status is something for UserUtil::loginUsing() to deal with after we
                // tell it whether the account authenticates or not.
                $authenticatedUid = UserUtil::getIdFromEmail($loginID, true);
            }
        } else {
            $authenticatedUid = UserUtil::getIdFromName($loginID);
            if (!$authenticatedUid) {
                // Might be a registration. See above.
                $authenticatedUid = UserUtil::getIdFromName($loginID, true);
            }
        }

        return $authenticatedUid;
    }
Esempio n. 20
0
 public function  applyCsvValues($args){
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_DELETE));
     $update = isset($args['update'])?$args['update']:null;
     $insert = isset($args['insert'])?$args['insert']:null;
     
     // Upate users table with new values
     if (!(DBUtil::updateObjectArray($update, 'users', 'uid')))
             LogUtil::registerError($this->__('Error! Update attempt failed.'));
     // Update IWusers table
     foreach ($update as &$user){
         if (DBUtil::updateObject($user, 'IWusers', "iw_uid =".$user['uid']))
             $user['action'] = 'm'; // modified //$this->__('Update');
         else 
             $user['error']= $user['uname']." - ".$this->__('Error! Update attempt failed.'). " ";
     }
     if (count($insert)){
         // Create new users in users table
         if (!(DBUtil::InsertObjectArray($insert, 'users', 'uid')))
             LogUtil::registerError($this->__('Error! New user creation attempt failed.'));
         // Create new users in IWusers table
         if (!(DBUtil::InsertObjectArray($insert, 'IWusers')))
             LogUtil::registerError($this->__('Error! New user creation attempt failed.'));
     }
     // Join update and insert arrays and process 
     $allChanges = array_merge($update, $insert);
    
     foreach ($allChanges as &$user){
         // Process "in" and "out" groups information
         ModUtil::apiFunc($this->name, 'admin', 'updateUserGroups', $user);
         // Set user pass
         if (isset($user['password']) && ($user['password']!="")) {
             // Validate pass length and pass <> uname or new_uname
             if (userUtil::validatePassword($user['password'])) {
                 UserUtil::setPassword($user['password'], $user['uid']);
             } else {
                 // Not a valid password -> error
                 $result['error'][$user['uid']] = $user;
                 $user['error'].=  $this->__('Password does not meet the minimum criteria.')." ";                    
             }
         }        
         // Force user change password?
         if ($forcechgpass) {
             switch ($user['forcechgpass']) {
                 case 1:
                     UserUtil::setVar('_Users_mustChangePassword', 1, $user['uid']);
                     break;
                 case 0;
                     UserUtil::delVar('_Users_mustChangePassword', $user['uid']);
                     break;
             }
         }
         // Change uname
         if (isset($user['new_uname']) && ($user['new_uname']!= "") && (!is_null($user['uid']))) {
             // search repeated uname/new_uname
             if (!(UserUtil::getIdFromName($user['new_uname']))) { 
                 // new_uname not exists proceed with uname change
                 $object['uname'] = $user['new_uname'];
                 //$object['uid'] = $user['uid'];
                 DBUtil::updateObject($object, 'users', "uid=".$user['uid']);
                 //UserUtil::setPassword($user['pass'], $user['uid']);
             } else {
                  $user['error'].=  $this->__f('Duplicated username: %s.', $user['new_uname']);
             }    
         }       
     }
     return $allChanges;
 }
Esempio n. 21
0
/**
 * Get the uid of a user from the username
 *
 * @deprecated
 * @see UserUtil::getIdFromName()
 *
 * @param uname $ the username
 * @return mixed userid if found, false if not
 */
function pnUserGetIDFromName($uname)
{
    LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(__FUNCTION__, 'UserUtil::getIdFromName()')), E_USER_DEPRECATED);
    return UserUtil::getIdFromName($uname);
}