<?php

/** @const TURBA_SEARCH_AND. Boolean 'and' search. */ define('TURBA_SEARCH_AND', 1);
/** @const TURBA_SEARCH_OR Boolean 'or' search.    */ define('TURBA_SEARCH_OR', 2);

/**
 * Turba Base Class.
 *
 * $Horde: turba/lib/Turba.php,v 1.36 2003/06/17 22:28:01 slusarz Exp $
 *
 * @author Chuck Hagenbuch <chuck@horde.org>
 * @author Jon Parise <jon@horde.org>
 * @version $Revision: 1.36 $
 * @package turba
 */
class Turba {

    function getBareEmail($address)
    {
        require_once 'Mail/RFC822.php';
        require_once HORDE_BASE . '/lib/MIME.php';

        static $rfc822;
        if (is_null($rfc822)) {
            $rfc822 = new Mail_RFC822();
        }

        $rfc822->validateMailbox($address);

        return MIME::rfc822WriteAddress($address->mailbox, $address->host);
    }

    function formatEmailAddresses($data, &$ob)
    {
        require_once HORDE_BASE . '/lib/MIME.php';

        $email_vals = explode(',', $data);
        $email_values = false;
        foreach ($email_vals as $email_val) {
            $email_val = trim($email_val);

            // Format the address according to RFC822.
            $mailbox_host = explode('@', $email_val);
            if (!isset($mailbox_host[1])) {
                $mailbox_host[1] = '';
            }
            $name = $ob->getValue('name');
            $address = MIME::rfc822WriteAddress($mailbox_host[0], $mailbox_host[1], $name);

            // Get rid of the trailing @ (when no host is included in
            // the email address).
            $address = str_replace('@>', '>', $address);
            $mail_link = $GLOBALS['registry']->call('mail/compose', array(array('to' => addslashes($address))));
            if (is_a($mail_link, 'PEAR_Error')) {
                $mail_link = 'mailto:' . urlencode($address);
            }

            $email_value = Horde::link($mail_link, $email_val) . htmlspecialchars($email_val) . '</a>';
            if ($email_values) {
                $email_values .= ', ' . $email_value;
            } else {
                $email_values = $email_value;
            }
        }

        return $email_values;
    }

    function string2Columns($string)
    {
        $ret = array();
        $lines = explode("\n", $string);
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line)) {
                $columns = explode("\t", $line);
                if (count($columns) > 1) {
                    $source = array_splice($columns, 0, 1);
                    $ret[$source[0]] = $columns;
                }
            }
        }

        return $ret;
    }

    function columns2String($hash)
    {
        foreach ($hash as $source => $columns) {
            if (isset($string)) {
                $string .= "\n";
            } else {
                $string = '';
            }
            $line = '';
            foreach ($columns as $column) {
                if (!empty($line)) {
                    $line .= "\t";
                }
                $line .= $column;
            }
        }

        return $string;
    }

    function wapFormat($phoneNumber)
    {
        $phoneNumber = preg_replace('|[ .()-]|', '', $phoneNumber);
        $phoneNumber = preg_replace('|ext(.)*|', '', $phoneNumber);

        return $phoneNumber;
    }

    /**
     * Returns a best guess at the lastname in a string.
     *
     * @param $name     String contain the full name.
     *
     * @return          String containing the last name.
     */
    function guessLastname($name)
    {
        if (!empty($name)) {
            /* Assume that last names are always before any commas. */
            if (is_int(strpos($name, ','))) {
                $name = String::substr($name, 0, strpos($name, ','));
            }

            /* Take out anything in parentheses. */
            $name = preg_replace('|\(.*\)|', '', $name);

            $name = trim(preg_replace('|\s+|', ' ', $name));
            $namelist = explode(' ', $name);
            $name = $namelist[($nameindex = (count($namelist) - 1))];

            while (String::length($name) < 5 &&
                   strspn($name[(String::length($name) - 1)], '.:-') &&
                   isset($namelist[($nameindex - 1)])) {
                $nameindex--;
                $name = $namelist[$nameindex];
            }
        }
        return $name;
    }

    /**
     * Formats the name according to the user's preference.
     *
     * @param string $name  The full name.
     * @return string       The formatted name, either "Firstname Lastname"
     *                      or "Lastname, Firstname" depending on the user's
     *                      preference.
     */
    function formatName($name)
    {
        global $prefs;

        $format = $prefs->getValue('name_format');
        $lastname = Turba::guessLastname($name);
        if ($format == 'last_first' &&
            !is_int(strpos($name, ',')) &&
            String::length($name) > String::length($lastname)) {
            $name = preg_replace("|\s+$lastname|", '', $name);
            $name = $lastname . ', ' . $name;
        }
        if ($format == 'first_last' &&
            is_int(strpos($name, ',')) &&
            String::length($name) > String::length($lastname)) {
            $name = preg_replace("|$lastname,\s*|", '', $name);
            $name = $name . ' ' . $lastname;
        }
        return $name;
    }

    /**
     * Checks if a user has the specified permissions on the passed-in
     * object.
     *
     * @param array $in        The data to check on.
     * @param string $filter   What are we checking for.
     * @param int $permission  What permission to check for.
     *
     * @return array           An array containing the criteria.
     */
    function checkPermissions($in, $filter, $permission = _PERMS_READ)
    {
        $userID = Auth::getAuth();
        $admin = Auth::isAdmin();
        if ($admin || in_array($userID, $in->source->admin)) {
            return true;
        }

        switch ($filter) {
        case 'object':
            switch ($permission) {
            case _PERMS_SHOW:
            case _PERMS_READ:
                if ($in->source->public ||
                        ($in->hasValue('__owner') &&
                        $in->getValue('__owner') == $userID)) {
                    return true;
                }
                break;

            case _PERMS_EDIT:
            case _PERMS_DELETE:
                /* Find out if this is a case that the object is
                 * editable. */
                if (!$in->source->readonly &&
                    $in->hasValue('__owner') &&
                    $in->getValue('__owner') == $userID) {
                    return true;
                }
                return false;
                break;
            }
            break;

        default:
            return true;
        }

        return false;
    }

    function menu()
    {
        global $conf, $registry, $notification;
        require_once HORDE_BASE . '/lib/Menu.php';
        require TURBA_TEMPLATES . '/menu/menu.inc';

        $notification->notify();

        /* Include the JavaScript for the help system. */
        Help::javascript();
    }

}
