Ejemplo n.º 1
0
/**
 * Override theme_username() function.
 * Removes the text '(not verified)' for anonymous users.
 */
function quickdrupal_username($object)
{
    if ($object->uid && $object->name) {
        if (drupal_strlen($object->name) > 20) {
            $name = drupal_substr($object->name, 0, 15) . '...';
        } else {
            $name = $object->name;
        }
        if (user_access('access user profiles')) {
            $output = l($name, 'user/' . $object->uid, array('attributes' => array('title' => t('View user profile.'))));
        } else {
            $output = check_plain($name);
        }
    } else {
        if ($object->name) {
            if (!empty($object->homepage)) {
                $output = l($object->name, $object->homepage, array('attributes' => array('rel' => 'nofollow')));
            } else {
                $output = check_plain($object->name);
            }
        } else {
            $output = check_plain(variable_get('anonymous', t('Anonymous')));
        }
    }
    return $output;
}
/**
 * Convert project repository data.
 */
function cvs_to_versioncontrol_project_update_2()
{
    // This determines how many projects will be processed in each batch run. A reasonable
    // default has been chosen, but you may want to tweak depending on your setup.
    $limit = 100;
    // Multi-part update
    if (!isset($_SESSION['cvs_to_versioncontrol_project_update_2'])) {
        $_SESSION['cvs_to_versioncontrol_project_update_2'] = 0;
        $_SESSION['cvs_to_versioncontrol_project_update_2_max'] = db_result(db_query("SELECT COUNT(*) FROM {cvs_projects}"));
    }
    // Pull the next batch of users.
    $projects = db_query_range("SELECT p.nid, p.rid, p.directory, r.modules FROM {cvs_projects} p INNER JOIN {cvs_repositories} r ON p.rid = r.rid ORDER BY p.nid", $_SESSION['cvs_to_versioncontrol_project_update_2'], $limit);
    // Loop through each project.
    while ($project = db_fetch_object($projects)) {
        // Add the repo module, and chop off the trailing slash.
        $directory = '/' . trim($project->modules) . drupal_substr($project->directory, 0, drupal_strlen($project->directory) - 1);
        db_query("INSERT INTO {versioncontrol_project_projects} (nid, repo_id, directory) VALUES (%d, %d, '%s')", $project->nid, $project->rid, $directory);
        $_SESSION['cvs_to_versioncontrol_project_update_2']++;
    }
    if ($_SESSION['cvs_to_versioncontrol_project_update_2'] >= $_SESSION['cvs_to_versioncontrol_project_update_2_max']) {
        $count = $_SESSION['cvs_to_versioncontrol_project_update_2_max'];
        unset($_SESSION['cvs_to_versioncontrol_project_update_2']);
        unset($_SESSION['cvs_to_versioncontrol_project_update_2_max']);
        return array(array('success' => TRUE, 'query' => t('Converted @count project repository entries.', array('@count' => $count))));
    }
    return array('#finished' => $_SESSION['cvs_to_versioncontrol_project_update_2'] / $_SESSION['cvs_to_versioncontrol_project_update_2_max']);
}
/**
 * Calls a transaction request
 */
function ideal_payment_api_transreq_call($order)
{
    //Get user ID
    global $user;
    if ($user) {
        $user_id = $user->uid;
    }
    $path_module = drupal_get_path('module', 'ideal_payment_api');
    require_once $path_module . '/lib/iDEALConnector.php';
    $iDEALConnector = new iDEALConnector();
    $order['description'] = check_plain($order['description']);
    if (drupal_strlen($order['description']) > 32) {
        //@TODO: run this trough a general error handler.
        $order['description_orig'] = $order['description'];
        $order['description'] = drupal_substr($order['description'], 0, 32);
        watchdog('ideal_api', t('iDEAL decription too long. Changed from %orig to %shortened', array('%orig' => $order['description_orig'], '%shortened' => $order['description'])));
    }
    //issuerid is min. 4 chars, add leading 0's
    $order['issuer_id'] = str_pad($order['issuer_id'], 4, '0', STR_PAD_LEFT);
    //Send TransactionRequest
    $response = $iDEALConnector->RequestTransaction($order['issuer_id'], $order['order_id'], $order['amount'], $order['description'], $order['order_id'], $iDEALConnector->config['EXPIRATIONPERIOD'], $iDEALConnector->config['MERCHANTRETURNURL']);
    if (!$response->errCode) {
        return $response;
    } else {
        watchdog('ideal_api', $response->errCode . ': ' . $response->errMsg, NULL, WATCHDOG_ERROR);
        return $response;
    }
}
Ejemplo n.º 4
0
function set_media_vars($node, $identifier = "") {
  $title = $node->title;
  if (drupal_strlen($identifier))
    $link = "/ia/details/". $identifier;
  else
    $link = "/node/". $node->nid;
  $mediaurl = $node->field_default_file[0]['value'];
  if (!drupal_strlen($mediaurl)) {  // get it from attachments
   $cnt = 0;
   foreach ($node->files as $file) {
     $cnt++;
     if (count($node->files) == 1) 
       $mediaurl = $file->filepath; // if only one file, use it
     elseif (strpos($file->description, "/original/") !== FALSE) {
       $mediaurl = $file->filepath; // found original tag
       break;
     } 
     elseif (strpos($filename, "_files.xml") || strpos($filename, "_meta.xml") )
       $mediaurl = $file->filepath; // avoid _meta.xml and _files.xml files
     elseif ($cnt == 1)
       $mediaurl = $file->filepath; // always use the first file if no other hint
   }
  }
  if ((strpos($mediaurl, "internetarchive/") !== FALSE) && (strpos($mediaurl, "http://") !== 0))
    $mediaurl = str_replace("internetarchive/", "http://www.archive.org/download/", $mediaurl);    
  return array('mediaurl' => $mediaurl, 'title' => $title, 'link' => $link);
}
Ejemplo n.º 5
0
function phptemplate_username($object)
{
    if ($object->uid && $object->name) {
        // Shorten the name when it is too long or it will break many tables.
        if (arg(0) == 'user' or 'groups') {
            $name = $object->name;
        } else {
            if (drupal_strlen($object->name) > 20) {
                $name = drupal_substr($object->name, 0, 15) . '...';
            } else {
                $name = $object->name;
            }
        }
        if (user_access('access user profiles')) {
            $output = l($name, 'user/' . $object->uid, array('title' => t('View user profile.')));
        } else {
            $output = check_plain($name);
        }
    } else {
        if ($object->name) {
            // Sometimes modules display content composed by people who are
            // not registered members of the site (e.g. mailing list or news
            // aggregator modules). This clause enables modules to display
            // the true author of the content.
            if ($object->homepage) {
                $output = l($object->name, $object->homepage, array('class' => 'anonymous', 'title' => t('not verified')));
            } else {
                $output = '<span class="anonymous" title="' . t('not verified') . '">' . check_plain($object->name) . '</span>';
            }
        } else {
            $output = variable_get('anonymous', t('Anonymous'));
        }
    }
    return $output;
}
/**
 * Apply advanced options to a generated member id string.
 */
function _membership_entity_token_clean_string($string, $settings)
{
    // Remove all HTML tags from the string.
    $return = strip_tags(decode_entities($string));
    // Get rid of words that are on the ignore list
    $ignore_words = $settings['ignore_words'];
    $ignore_words_regex = preg_replace(array('/^[,\\s]+|[,\\s]+$/', '/[,\\s]+/'), array('', '\\b|\\b'), $ignore_words);
    if ($ignore_words_regex) {
        $ignore_words_regex = '/\\b' . $ignore_words_regex . '\\b/i';
        $words_removed = preg_replace($ignore_words_regex, '', $return);
        if (drupal_strlen(trim($words_removed)) > 0) {
            $return = $words_removed;
        }
    }
    // Replace whitespace with the separator.
    $return = _membership_entity_token_clean_separator($return, $settings['separator']);
    // Convert to lower or upper case.
    if ($settings['case'] == 'lower') {
        $return = drupal_strtolower($return);
    } else {
        if ($settings['case'] == 'upper') {
            $return = drupal_strtoupper($return);
        }
    }
    // Shorten to maxlength.
    if (!empty($settings['maxlength'])) {
        $return = truncate_utf8($return, $settings['maxlength']);
    }
    return $return;
}
 /**
  * @see LdapAuthorizationConsumerAbstract::createConsumer
  */
 public function createConsumer($consumer_id, $consumer)
 {
     $roles_by_consumer_id = $this->existingRolesByRoleName();
     $existing_role = isset($roles_by_consumer_id[$consumer_id]) ? $roles_by_consumer_id[$consumer_id] : FALSE;
     if ($existing_role) {
         return FALSE;
         // role exists
     } elseif (drupal_strlen($consumer_id) > 63) {
         watchdog('ldap_authorization_drupal_role', 'Tried to create drupal role
     with name of over 63 characters (%group_name).  Please correct your
     drupal ldap_authorization settings', array('%group_name' => $consumer_id));
         return FALSE;
     }
     $new_role = new stdClass();
     $new_role->name = empty($consumer['value']) ? $consumer_id : $consumer['value'];
     if (!($status = user_role_save($new_role))) {
         // if role is not created, remove from array to user object doesn't have it stored as granted
         watchdog('user', 'failed to create drupal role %role in ldap_authorizations module', array('%role' => $new_role->name));
         return FALSE;
     } else {
         $roles_by_consumer_id = $this->existingRolesByRoleName(TRUE);
         // flush existingRolesByRoleName cache after creating new role
         watchdog('user', 'created drupal role %role in ldap_authorizations module', array('%role' => $new_role->name));
     }
     return TRUE;
 }
 /**
  * Updates a text
  *
  * @param int $nid ["path","0"]
  *  The nid of the text to update
  * @param object $text ["data"]
  *  The text object
  * @return object
  *
  * @Access(callback='DocuWalkTextResource::access', args={'update'}, appendArgs=true)
  */
 public static function update($nid, $text)
 {
     $attr = array('body');
     $node = node_load($nid);
     // Transfer attributes from
     foreach ($attr as $name) {
         if (isset($text->{$name})) {
             $node->{$name} = $text->{$name};
         }
     }
     $text->title = drupal_substr($text->body, 0, min(drupal_strlen($text->body), 40));
     node_save($node);
     return (object) array('nid' => $node->nid, 'uri' => services_resource_uri(array('docuwalk-text', $node->nid)), 'url' => url('node/' . $node->nid, array('absolute' => TRUE)));
 }
Ejemplo n.º 9
0
/**
 * Acts on requests to the server defined in hook_server_info().
 *
 * This is the main entry point to your server implementation.
 * Need to get some more description about the best way to implement
 * servers.
 */
function hook_server()
{
    $endpoint_path = services_get_server_info('endpoint_path', 'services/rest');
    $canonical_path = trim(drupal_substr($_GET['q'], drupal_strlen($endpoint_path)), '/');
    $canonical_path = explode('/', $_GET['q']);
    $endpoint_path_count = count(explode('/', $endpoint_path));
    for ($x = 0; $x < $endpoint_path_count; $x++) {
        array_shift($canonical_path);
    }
    $canonical_path = implode('/', $canonical_path);
    if (empty($canonical_path)) {
        return '';
    }
    //Handle server based on $canonical_path
}
 /**
  * Tests that all Unicode characters simplify correctly.
  */
 function testSearchSimplifyUnicode()
 {
     // This test uses a file that was constructed so that the even lines are
     // boundary characters, and the odd lines are valid word characters. (It
     // was generated as a sequence of all the Unicode characters, and then the
     // boundary chararacters (punctuation, spaces, etc.) were split off into
     // their own lines).  So the even-numbered lines should simplify to nothing,
     // and the odd-numbered lines we need to split into shorter chunks and
     // verify that simplification doesn't lose any characters.
     $input = file_get_contents(DRUPAL_ROOT . '/core/modules/search/tests/UnicodeTest.txt');
     $basestrings = explode(chr(10), $input);
     $strings = array();
     foreach ($basestrings as $key => $string) {
         if ($key % 2) {
             // Even line - should simplify down to a space.
             $simplified = search_simplify($string);
             $this->assertIdentical($simplified, ' ', "Line {$key} is excluded from the index");
         } else {
             // Odd line, should be word characters.
             // Split this into 30-character chunks, so we don't run into limits
             // of truncation in search_simplify().
             $start = 0;
             while ($start < drupal_strlen($string)) {
                 $newstr = drupal_substr($string, $start, 30);
                 // Special case: leading zeros are removed from numeric strings,
                 // and there's one string in this file that is numbers starting with
                 // zero, so prepend a 1 on that string.
                 if (preg_match('/^[0-9]+$/', $newstr)) {
                     $newstr = '1' . $newstr;
                 }
                 $strings[] = $newstr;
                 $start += 30;
             }
         }
     }
     foreach ($strings as $key => $string) {
         $simplified = search_simplify($string);
         $this->assertTrue(drupal_strlen($simplified) >= drupal_strlen($string), "Nothing is removed from string {$key}.");
     }
     // Test the low-numbered ASCII control characters separately. They are not
     // in the text file because they are problematic for diff, especially \0.
     $string = '';
     for ($i = 0; $i < 32; $i++) {
         $string .= chr($i);
     }
     $this->assertIdentical(' ', search_simplify($string), 'Search simplify works for ASCII control characters.');
 }
Ejemplo n.º 11
0
 /**
  * Build a row based on the item.
  *
  * By default all of the rows are placed into a table by the render
  * method, so this is building up a row suitable for theme('table').
  * This doesn't have to be true if you override both.
  */
 function list_build_row($item, &$form_state, $operations)
 {
     // Set up sorting
     $name = $item->{$this->plugin['export']['key']};
     $schema = ctools_export_get_schema($this->plugin['schema']);
     // Load Custom Formatters engines.
     $engines = module_invoke_all('custom_formatters_engine_info');
     // Hide Formatters using missing engines.
     if (!isset($engines[$item->mode])) {
         unset($this->row);
         return;
     }
     // Note: $item->{$schema['export']['export type string']} should have already been set up by export.inc so
     // we can use it safely.
     switch ($form_state['values']['order']) {
         case 'disabled':
             $this->sorts[$name] = empty($item->disabled) . $name;
             break;
         case 'title':
             $this->sorts[$name] = $item->{$this->plugin['export']['admin_title']};
             break;
         case 'name':
             $this->sorts[$name] = $name;
             break;
         case 'storage':
             $this->sorts[$name] = $item->{$schema['export']['export type string']} . $name;
             break;
     }
     $this->rows[$name]['data'] = array();
     $this->rows[$name]['class'] = !empty($item->disabled) ? array('ctools-export-ui-disabled') : array('ctools-export-ui-enabled');
     // If we have an admin title, make it the first row.
     if (!empty($this->plugin['export']['admin_title'])) {
         $this->rows[$name]['data'][] = array('data' => check_plain($item->{$this->plugin['export']['admin_title']}), 'class' => array('ctools-export-ui-title'));
     }
     $this->rows[$name]['data'][] = array('data' => check_plain($name), 'class' => array('ctools-export-ui-name'));
     $this->rows[$name]['data'][] = array('data' => check_plain($engines[$item->mode]['label']), 'class' => array('ctools-export-ui-format'));
     $this->rows[$name]['data'][] = array('data' => !empty($item->fapi) && drupal_strlen($item->fapi) > 17 ? t('Yes') : t('No'), 'class' => array('ctools-export-ui-fapi'));
     $this->rows[$name]['data'][] = array('data' => check_plain($item->{$schema['export']['export type string']}), 'class' => array('ctools-export-ui-storage'));
     $ops = theme('links__ctools_dropbutton', array('links' => $operations, 'attributes' => array('class' => array('links', 'inline'))));
     $this->rows[$name]['data'][] = array('data' => $ops, 'class' => array('ctools-export-ui-operations'));
     // Add an automatic mouseover of the description if one exists.
     if (!empty($this->plugin['export']['admin_description'])) {
         $this->rows[$name]['title'] = $item->{$this->plugin['export']['admin_description']};
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validate($name, Constraint $constraint)
 {
     if (!$name) {
         $this->context->addViolation($constraint->emptyMessage);
         return;
     }
     if (substr($name, 0, 1) == ' ') {
         $this->context->addViolation($constraint->spaceBeginMessage);
     }
     if (substr($name, -1) == ' ') {
         $this->context->addViolation($constraint->spaceEndMessage);
     }
     if (strpos($name, '  ') !== FALSE) {
         $this->context->addViolation($constraint->multipleSpacesMessage);
     }
     if (preg_match('/[^\\x{80}-\\x{F7} a-z0-9@_.\'-]/i', $name) || preg_match('/[\\x{80}-\\x{A0}' . '\\x{AD}' . '\\x{2000}-\\x{200F}' . '\\x{2028}-\\x{202F}' . '\\x{205F}-\\x{206F}' . '\\x{FEFF}' . '\\x{FF01}-\\x{FF60}' . '\\x{FFF9}-\\x{FFFD}' . '\\x{0}-\\x{1F}]/u', $name)) {
         $this->context->addViolation($constraint->illegalMessage);
     }
     if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
         $this->context->addViolation($constraint->tooLongMessage, array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
     }
 }
Ejemplo n.º 13
0
 /**
  * Log last request, if logging is enabled.
  *
  * @param ...
  *   A variable number of arguments, whose values will be redacted.
  */
 private function log()
 {
     if ($this->logging) {
         timer_stop('openruth_net');
         if ($this->log_timestamp) {
             $time = round(microtime(TRUE) - $this->log_timestamp, 2);
             $this->log_timestamp = NULL;
         }
         $sensitive = func_get_args();
         // For some reason PHP doesn't have array_flatten, and this is the
         // shortest alternative.
         $replace_values = array();
         foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($sensitive)) as $value) {
             $replace_values['>' . $value . '<'] = '>' . drupal_substr(md5($value . self::$salt), 0, drupal_strlen($value)) . '<';
         }
         if (isset($time)) {
             watchdog('openruth', 'Sending request (@seconds sec): @xml', array('@xml' => strtr($this->client->__getLastRequest(), $replace_values), '@seconds' => $time), WATCHDOG_DEBUG);
         } else {
             watchdog('openruth', 'Sending request: @xml', array('@xml' => strtr($this->client->__getLastRequest(), $replace_values)), WATCHDOG_DEBUG);
         }
         watchdog('openruth', 'Response: @xml', array('@xml' => strtr($this->client->__getLastResponse(), $replace_values)), WATCHDOG_DEBUG);
     }
 }
Ejemplo n.º 14
0
function ninesixtyrobots_username($object)
{
    if ($object->uid && $object->name && module_exists('profile')) {
        profile_load_profile($object);
        if (!empty($object->profile_real_name)) {
            $object->name = $object->profile_real_name;
        }
        // Shorten the name when it is too long or it will break many tables.
        if (drupal_strlen($object->name) > 20) {
            $name = drupal_substr($object->name, 0, 15) . '...';
        } else {
            $name = $object->name;
        }
        if (user_access('access user profiles')) {
            $output = l($name, 'user/' . $object->uid, array('attributes' => array('title' => t('View user profile.'))));
        } else {
            $output = check_plain($name);
        }
    } else {
        if ($object->name) {
            // Sometimes modules display content composed by people who are
            // not registered members of the site (e.g. mailing list or news
            // aggregator modules). This clause enables modules to display
            // the true author of the content.
            if (!empty($object->homepage)) {
                $output = l($object->name, $object->homepage, array('attributes' => array('rel' => 'nofollow')));
            } else {
                $output = check_plain($object->name);
            }
            $output .= ' (' . t('not verified') . ')';
        } else {
            $output = variable_get('anonymous', t('Anonymous'));
        }
    }
    return $output;
}
 /**
  * extends createConsumer method of base class
  *
  * creates of drupal roles may be mixed case.  drupal doesn't
  * differentiate, so case is ignored in comparing, but preserved
  * for the actual created role name saved.
  *
  * **/
 public function createConsumers($roles_to_create)
 {
     // 1. determins difference between existing drupal roles and ones that are requested to be created
     $existing_roles_lower_case = array_keys($this->availableConsumerIDs());
     $roles_to_create_lcase = array_unique(array_diff(array_keys($roles_to_create), $existing_roles_lower_case));
     // 2. create each role that is needed
     foreach ($roles_to_create_lcase as $i => $role_name_lowercase) {
         $role_name = $roles_to_create[$role_name_lowercase];
         if (drupal_strlen($role_name_lowercase) > 63) {
             watchdog('ldap_authorization_drupal_role', 'Tried to create drupal role with name of over 63 characters (%group_name).  Please correct your drupal ldap_authorization settings', array('%group_name' => $role_name_lowercase));
             continue;
         }
         $role = new stdClass();
         $role->name = $role_name;
         if (!($status = user_role_save($role))) {
             // if role is not created, remove from array to user object doesn't have it stored as granted
             watchdog('user', 'failed to create drupal role %role in ldap_authorizations module', array('%role' => $role->name));
         } else {
             $created[] = $role->name;
             watchdog('user', 'created drupal role %role in ldap_authorizations module', array('%role' => $role->name));
         }
     }
     // 3. return all existing user roles and flush cache of consumer ids.
     $refreshed_available_consumer_ids = $this->availableConsumerIDs(TRUE);
     if ($this->detailedWatchdogLog) {
         $watchdog_tokens = array('%roles_to_create' => join(", ", $roles_to_create_lcase));
         $watchdog_tokens = array('%existing_roles' => join(", ", $existing_roles_lower_case));
         $watchdog_tokens = array('%refreshed_available_consumer_ids' => join(", ", array_keys($refreshed_available_consumer_ids)));
         watchdog('ldap_authorization', 'LdapAuthorizationConsumerDrupalRole.createConsumers()
     roles to create: %roles_to_create;
     existing roles: %existing_roles;
     available roles after createConsumers call: %refreshed_available_consumer_ids;', $watchdog_tokens, WATCHDOG_DEBUG);
     }
     return $refreshed_available_consumer_ids;
     // return actual roles that exist, in case of failure
 }
Ejemplo n.º 16
0
 /**
  * Trims the field down to the specified length.
  *
  * @param array $alter
  *   The alter array of options to use.
  *     - max_length: Maximum length of the string, the rest gets truncated.
  *     - word_boundary: Trim only on a word boundary.
  *     - ellipsis: Show an ellipsis (…) at the end of the trimmed string.
  *     - html: Make sure that the html is correct.
  *
  * @param string $value
  *   The string which should be trimmed.
  *
  * @return string
  *   The trimmed string.
  */
 public static function trimText($alter, $value)
 {
     if (drupal_strlen($value) > $alter['max_length']) {
         $value = drupal_substr($value, 0, $alter['max_length']);
         if (!empty($alter['word_boundary'])) {
             $regex = "(.*)\\b.+";
             if (function_exists('mb_ereg')) {
                 mb_regex_encoding('UTF-8');
                 $found = mb_ereg($regex, $value, $matches);
             } else {
                 $found = preg_match("/{$regex}/us", $value, $matches);
             }
             if ($found) {
                 $value = $matches[1];
             }
         }
         // Remove scraps of HTML entities from the end of a strings
         $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));
         if (!empty($alter['ellipsis'])) {
             $value .= t('…');
         }
     }
     if (!empty($alter['html'])) {
         $value = Html::normalize($value);
     }
     return $value;
 }
Ejemplo n.º 17
0
/**
 * Override the username theme function so that it returns a display name
 * rather than the unique Drupal auth name
 */
function phptemplate_username($object)
{
    if ($object->uid && $object->name) {
        // Show the profile name in general, not the username
        $name = user_load($object->uid)->boincuser_name;
        // Shorten the name when it is too long or it will break many tables.
        if (drupal_strlen($name) > 20) {
            $name = drupal_substr($name, 0, 15) . '...';
        }
        if (user_access('access user profiles')) {
            $output = l($name, 'account/' . $object->uid, array('attributes' => array('title' => bts('View user profile.'))));
        } else {
            $output = check_plain($name);
        }
    } else {
        if ($object->name) {
            // Sometimes modules display content composed by people who are
            // not registered members of the site (e.g. mailing list or news
            // aggregator modules). This clause enables modules to display
            // the true author of the content.
            if (!empty($object->homepage)) {
                $output = l($object->name, $object->homepage, array('attributes' => array('rel' => 'nofollow')));
            } else {
                $output = check_plain($object->name);
            }
            $output .= ' (' . bts('not verified') . ')';
        } else {
            $output = check_plain(variable_get('anonymous', bts('Anonymous')));
        }
    }
    return $output;
}
Ejemplo n.º 18
0
 /**
  * Creates a custom menu.
  *
  * @return \Drupal\system\Entity\Menu
  *   The custom menu that has been created.
  */
 function addCustomMenu()
 {
     // Try adding a menu using a menu_name that is too long.
     $this->drupalGet('admin/structure/menu/add');
     $menu_name = substr(hash('sha256', $this->randomMachineName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI + 1);
     $label = $this->randomMachineName(16);
     $edit = array('id' => $menu_name, 'description' => '', 'label' => $label);
     $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save'));
     // Verify that using a menu_name that is too long results in a validation
     // message.
     $this->assertRaw(t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => t('Menu name'), '%max' => MENU_MAX_MENU_NAME_LENGTH_UI, '%length' => drupal_strlen($menu_name))));
     // Change the menu_name so it no longer exceeds the maximum length.
     $menu_name = substr(hash('sha256', $this->randomMachineName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI);
     $edit['id'] = $menu_name;
     $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save'));
     // Verify that no validation error is given for menu_name length.
     $this->assertNoRaw(t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => t('Menu name'), '%max' => MENU_MAX_MENU_NAME_LENGTH_UI, '%length' => drupal_strlen($menu_name))));
     // Verify that the confirmation message is displayed.
     $this->assertRaw(t('Menu %label has been added.', array('%label' => $label)));
     $this->drupalGet('admin/structure/menu');
     $this->assertText($label, 'Menu created');
     // Confirm that the custom menu block is available.
     $this->drupalGet('admin/structure/block/list/' . \Drupal::config('system.theme')->get('default'));
     $this->assertText($label);
     // Enable the block.
     $this->drupalPlaceBlock('system_menu_block:' . $menu_name);
     return Menu::load($menu_name);
 }
Ejemplo n.º 19
0
a {
  text-decoration: none;
}
</style>

<?php if (drupal_strlen($href)) print "<a href='$href'>"; ?>

<center>

<div class='showcase_preview'>
  <div>
    <img class='thumb' src='<?php print $icon ?>' onload="this.src='<?php print $GLOBALS['ourmedia_base_url'] ?>/ia/thumbnail/<?php print $identifier ?>/2';" />
    <img class='thumb' src='<?php print $icon ?>' onload="this.src='<?php print $GLOBALS['ourmedia_base_url'] ?>/ia/thumbnail/<?php print $identifier ?>/3';" />
  </div>
  <div>
    <img class='thumb' src='<?php print $icon ?>' onload="this.src='<?php print $GLOBALS['ourmedia_base_url'] ?>/ia/thumbnail/<?php print $identifier ?>/4';" />
    <img class='thumb' src='<?php print $icon ?>' onload="this.src='<?php print $GLOBALS['ourmedia_base_url'] ?>/<?php print $identifier ?>/5';" />
  </div>
  <div class='playButton'>
    <img src="<?php print $directory ?>/images/playButton.png"/>
    <h1><?php print $message ?></h1>
  </div>
</div>

</center>

<?php

if (drupal_strlen($href))
  print "</a>";
<?php
// $Id$
/* @file
 * featured producer block items
 */
 
 if (!drupal_strlen($artistpicurl))
  $artistpicurl = $directory ."/images/omprofilegreengrassshadow.jpg";
?>

<div class='artist'>
  <a href="<?php echo $link ?>" title='Click to view artist homepage or profile'><img src='<?php echo $artistpicurl ?>' onerror='this.src="/<?php print $directory .'/images/producerImg.jpg' ?>";'/></a>
  <div>
    <label><a href="<?php print $variables['link'] ?>" title='Click to read post'><?php print $variables['title'] ?></a></label><br/>
<?php if (drupal_strlen($variables['author'])) { ?>
    by <a href="<?php print $variables['artisturl'] ?>" title='Click to view artist homepage or profile'><?php print $variables['author'] ?></a><br/>
<?php } ?>
    <p>
      <?php print $variables['description'] ?>
    </p>
  </div>
  <br/>
</div>
Ejemplo n.º 21
0
 /**
  * Parses a word or phrase for parseQuery().
  *
  * Splits a phrase into words. Adds its words to $this->words, if it is not
  * already there. Returns a list containing the number of new words found,
  * and the total number of words in the phrase.
  */
 protected function parseWord($word)
 {
     $num_new_scores = 0;
     $num_valid_words = 0;
     // Determine the scorewords of this word/phrase.
     $split = explode(' ', $word);
     foreach ($split as $s) {
         $num = is_numeric($s);
         if ($num || drupal_strlen($s) >= \Drupal::config('search.settings')->get('index.minimum_word_size')) {
             if (!isset($this->words[$s])) {
                 $this->words[$s] = $s;
                 $num_new_scores++;
             }
             $num_valid_words++;
         }
     }
     // Return matching snippet and number of added words.
     return array($num_new_scores, $num_valid_words);
 }
Ejemplo n.º 22
0
function _rootcandy_besturlmatch($needle, $menuitems)
{
    $needle = drupal_get_path_alias($needle);
    $lastmatch = NULL;
    $lastmatchlen = 0;
    $urlparts = explode('/', $needle);
    $partcount = count($urlparts);
    foreach ($menuitems as $key => $menuitem) {
        $href = $menuitem['href'];
        $menuurlparts = explode('/', $href);
        $matches = _rootcandy_countmatches($urlparts, $menuurlparts);
        if ($matches > $lastmatchlen || $matches == $lastmatchlen && ($lastmatch && drupal_strlen($menuitems[$lastmatch]['href'])) > drupal_strlen($href)) {
            $lastmatchlen = $matches;
            $lastmatch = $key;
        }
    }
    return $lastmatch;
}
function shib_auth_isDebug()
{
    return variable_get('shib_auth_debug_state', FALSE) && drupal_substr($_GET['q'], 0, drupal_strlen(variable_get('shib_auth_debug_url', ''))) == variable_get('shib_auth_debug_url', '');
}
Ejemplo n.º 24
0
/**
 * Define custom validate behavior for this module's field types.
 *
 * @param $obj_type
 *   The type of $object.
 * @param $object
 *   The object for the operation.
 *   Note that this might not be a full-fledged 'object'. When invoked through
 *   field_attach_query(), the $object will only include properties that the
 *   Field API knows about: bundle, id, revision id, and field values (no node
 *   title, user name...).
 * @param $field
 *   The field structure for the operation.
 * @param $instance
 *   The instance structure for $field on $object's bundle.
 * @param $langcode
 *   The language associated to $items.
 * @param $items
 *   $object->{$field['field_name']}[$langcode], or an empty array if unset.
 * @param $errors
 *   The array of errors, keyed by field name and by value delta, that have
 *   already been reported for the object. The function should add its errors
 *   to this array. Each error is an associative array, with the following
 *   keys and values:
 *   - 'error': an error code (should be a string, prefixed with the module name)
 *   - 'message': the human readable message to be displayed.
 */
function hook_field_validate($obj_type, $object, $field, $instance, $langcode, &$items, &$errors)
{
    foreach ($items as $delta => $item) {
        if (!empty($item['value'])) {
            if (!empty($field['settings']['max_length']) && drupal_strlen($item['value']) > $field['settings']['max_length']) {
                $errors[$field['field_name']][$delta][] = array('error' => 'text_max_length', 'message' => t('%name: the value may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length'])));
            }
        }
    }
}
Ejemplo n.º 25
0
 /**
  * Helper function to return a sanitized node title.
  */
 private static function get_node_title($node, $clip_and_decorate = FALSE)
 {
     if (isset($node)) {
         $nid = $node->id();
         if ($node_title = $node->title->value) {
             $node_title = SafeMarkup::checkPlain($node_title);
             if ($clip_and_decorate) {
                 if (drupal_strlen($node_title) > 20) {
                     $node_title = "<span title='node/{$nid}: {$node_title}'>" . drupal_substr($node_title, 0, 15) . '...</span>';
                 }
                 $node_title = '<span title="node/' . $nid . '">' . $node_title . '</span>';
             }
             return $node_title;
         } elseif ($nid) {
             return $nid;
         }
     }
     return '&mdash;';
 }
 /**
  * {@inheritdoc}
  */
 protected static function validateAllowedValue($option)
 {
     if (drupal_strlen($option) > 255) {
         return t('Allowed values list: each key must be a string at most 255 characters long.');
     }
 }
Ejemplo n.º 27
0
 /**
  * Bind (authenticate) against an active LDAP database.
  *
  * @param $userdn
  *   The DN to bind against. If NULL, we use $this->binddn
  * @param $pass
  *   The password search base. If NULL, we use $this->bindpw
  *
  * @return
  *   Result of bind; TRUE if successful, FALSE otherwise.
  */
 function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE)
 {
     // Ensure that we have an active server connection.
     if (!$this->connection) {
         watchdog('ldap', "LDAP bind failure for user %user. Not connected to LDAP server.", array('%user' => $userdn));
         return LDAP_CONNECT_ERROR;
     }
     if ($anon_bind !== FALSE && $userdn === NULL && $pass === NULL && $this->bind_method == LDAP_SERVERS_BIND_METHOD_ANON) {
         $anon_bind = TRUE;
     }
     if ($anon_bind === TRUE) {
         if (@(!ldap_bind($this->connection))) {
             if ($this->detailedWatchdogLog) {
                 watchdog('ldap', "LDAP anonymous bind error. Error %errno: %error", array('%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
             }
             return ldap_errno($this->connection);
         }
     } else {
         $userdn = $userdn != NULL ? $userdn : $this->binddn;
         $pass = $pass != NULL ? $pass : $this->bindpw;
         if ($this->followrefs) {
             $rebHandler = new LdapServersRebindHandler($userdn, $pass);
             ldap_set_rebind_proc($this->connection, array($rebHandler, 'rebind_callback'));
         }
         if (drupal_strlen($pass) == 0 || drupal_strlen($userdn) == 0) {
             watchdog('ldap', "LDAP bind failure for user userdn=%userdn, pass=%pass.", array('%userdn' => $userdn, '%pass' => $pass));
             return LDAP_LOCAL_ERROR;
         }
         if (@(!ldap_bind($this->connection, $userdn, $pass))) {
             if ($this->detailedWatchdogLog) {
                 watchdog('ldap', "LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
             }
             return ldap_errno($this->connection);
         }
     }
     return LDAP_SUCCESS;
 }
Ejemplo n.º 28
0
 private function _processContent()
 {
     if (strstr($this->rawContent, '<error') && !strstr($this->rawContent, '<ListRecords>')) {
         $text = $this->rawContent;
     } else {
         $text = $this->rawContent;
         if (!$this->need_debug) {
             $this->rawContent = '';
         }
     }
     $count = 0;
     $text = preg_replace("/^<\\?xml[^<>]+\\?>/", "", $text, -1, $count);
     if ($count != 1) {
         xc_log_error('regex', 'Malformed XML: no sheabang &mdash; ' . htmlentities($text));
         $this->parserErrors[] = 'no sheabang';
     }
     $count = 0;
     $text = preg_replace("/^\\s*<OAI-PMH\\b[^<>]+>/s", "", $text, -1, $count);
     if ($count != 1) {
         xc_log_error('regex', 'Malformed XML: no &lt;OAI-PMH&gt; &mdash; ' . htmlentities($text));
         $this->parserErrors[] = 'no OAI-PMH';
         return;
     }
     $count = 1;
     $text = preg_replace("/^\\s*<responseDate>(.*?)<\\/responseDate>/s", "", $text, -1, $count);
     if ($count != 1) {
         xc_log_error('regex', 'Malformed XML: no &lt;responseDate&gt; &mdash; ' . htmlentities($text));
         $this->parserErrors[] = 'no responseDate';
         return;
     }
     $count = 0;
     $text = preg_replace("/^\\s*<request(?: [^<>]+)?>(.*?)<\\/request>/s", "", $text, -1, $count);
     if ($count != 1) {
         xc_log_error('regex', 'Malformed XML: no &lt;request&gt; element in XML response: ' . htmlentities(substr($text, 0, 50)) . '&hellip;');
         $this->parserErrors[] = 'no request element';
         return;
     }
     $this->hasListRecords = FALSE;
     $this->hasErrors = FALSE;
     $count = 0;
     $text = preg_replace("/^\\s*<ListRecords>/", "", $text, -1, $count);
     if ($count != 1) {
         $errors = '';
         $size = drupal_strlen($text);
         $text = preg_replace_callback("/^\\s*<error(?: code=([\\'\"])(.*)([\\'\"]))?>(.*)<\\/error>/", array($this, 'setErrors'), $text);
         if ($size == drupal_strlen($text)) {
             xc_log_error('regex', 'Malformed XML: no ListRecords and no error elements &mdash; ' . htmlentities($text));
             $this->parserErrors[] = 'no ListRecords and error elements';
         } else {
             $this->hasErrors = TRUE;
         }
     } else {
         $this->hasListRecords = TRUE;
     }
     if (!$this->hasErrors && !$this->need_debug) {
         $this->rawContent = '';
     }
     if ($this->hasListRecords) {
         $resumption = '';
         $records = '';
         $is_changed_size = TRUE;
         while (!preg_match("/^\\s*<\\/ListRecords>/", $text) && $is_changed_size) {
             $count = 0;
             $text = preg_replace_callback("/^\\s*(<record>.*<\\/record>)/s", array($this, 'setRecords'), $text, -1, $count);
             if ($count > 0) {
                 $this->hasRecords = TRUE;
                 $is_changed_size = TRUE;
                 // raw_records is initialized by setRecords
                 $mod_records = str_replace('<record>', '<#######><record>', $this->raw_records);
                 $this->records = preg_split("/<#######>/", $mod_records, -1, PREG_SPLIT_NO_EMPTY);
                 $this->recordCount = count($this->records);
                 $mod_records = '';
                 $count = 0;
                 $text = preg_replace_callback("/^\\s*(<resumptionToken([^<>]*)>(.*?)<\\/resumptionToken>|<resumptionToken([^<>]*)\\s*\\/\\s*>)/", array($this, 'setResumption'), $text, -1, $count);
                 if ($count > 0) {
                     $is_changed_size = TRUE;
                     // resumption comes from setResumption
                     //echo 'recCount: ', $this->recordCount, ", resumption: ", $this->resumptionToken['text'], "\n";
                 } else {
                     $is_changed_size = FALSE;
                     //$this->parserErrors[] = 'no resumptionToken';
                 }
             } else {
                 $is_changed_size = FALSE;
                 $this->parserErrors[] = 'no record elements';
             }
         }
         // process inside ListRecords
         $count = 0;
         $text = preg_replace('/^\\s*<\\/ListRecords>/', '', $text, -1, $count);
         if ($count != 1) {
             xc_log_error('regex', 'Malformed XML: no /ListRecords &mdash; ' . htmlentities($text));
             $this->parserErrors[] = 'no ListRecords closer element';
         }
     } else {
         $this->parserErrors[] = 'no ListRecords element';
     }
     if ($this->hasListRecords || $this->hasErrors) {
         $count = 0;
         $text = preg_replace("/^\\s*<\\/OAI-PMH>/", '', $text, -1, $count);
         if ($count != 1) {
             xc_log_error('regex', 'Malformed XML: no /OAI-PMH &mdash; ' . htmlentities($text));
             $this->parserErrors[] = 'no /OAI-PMH closer element';
         }
     }
     // has ListRecords or error
 }
 /**
  * Implements hook_field_widget_form --> WidgetInterface::formElement().
  *
  * {@inheritdoc}
  *
  * Be careful: this widget may be shown in very different places. Test carefully!!
  *  - On a entity add/edit page
  *  - On a entity preview page
  *  - On a entity view page
  *  - On a entity 'workflow history' tab
  *  - On a comment display, in the comment history
  *  - On a comment form, below the comment history
  * @todo D8: change "array $items" to "FieldInterface $items"
  */
 public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state)
 {
     $field_name = $this->field['field_name'];
     $field = $this->instance;
     $instance = $this->instance;
     $entity = $this->entity;
     $entity_type = $this->entity_type;
     $entity_id = entity_id($entity_type, $entity);
     if (!$entity) {
         // If no entity given, do not show a form. E.g., on the field settings page.
         return $element;
     }
     // Capture settings to format the form/widget.
     $settings_title_as_name = !empty($this->field['settings']['widget']['name_as_title']);
     // The schedule cannot be shown on a Content add page.
     $settings_schedule = !empty($this->field['settings']['widget']['schedule']) && $entity_id;
     $settings_schedule_timezone = !empty($this->field['settings']['widget']['schedule_timezone']);
     // Show comment, when both Field and Instance allow this.
     $settings_comment = $this->field['settings']['widget']['comment'] ? 'textarea' : 'hidden';
     $workflow = Workflow::load($this->field['settings']['wid']);
     $current_sid = workflow_node_current_state($entity, $entity_type, $field_name);
     $current_state = WorkflowState::load($current_sid);
     $options = array();
     $options = $current_state->getOptions($entity_type, $entity);
     // Determine the default value. If we are in CreationState, use a fast alternative for $workflow->getFirstSid().
     $default_value = $current_state->isCreationState() ? key($options) : $current_sid;
     // Get the scheduling info. This may change the $current_sid on the Form.
     $scheduled = '0';
     $timestamp = REQUEST_TIME;
     $comment = NULL;
     if ($settings_schedule) {
         // Read scheduled information.
         // Technically you could have more than one scheduled, but this will only add the soonest one.
         foreach (WorkflowScheduledTransition::load($entity_type, $entity_id, $field_name) as $scheduled_transition) {
             $scheduled = '1';
             $current_sid = $scheduled_transition->sid;
             $timestamp = $scheduled_transition->scheduled;
             $comment = $scheduled_transition->comment;
             break;
         }
     }
     // Fetch the form ID. This is unique for each entity, to allow multiple form per page (Views, etc.).
     $form_id = $form_state['build_info']['form_id'];
     $element_scheduled_name = 'workflow_scheduled_' . $form_id;
     $element_options_name = 'workflow_options_' . $form_id;
     $element_scheduled_name = 'workflow_scheduled';
     $element_options_name = 'workflow_options';
     $elt_state_name = 'workflow_scheduled_' . $form_id;
     $label = $workflow->label();
     // Prepare a wrapper. This might be a fieldset.
     $element['workflow']['#type'] = 'container';
     $element['workflow']['#attributes'] = array('class' => array('workflow-form-container'));
     // Save the current value of the node in the form, for later Workflow-module specific references.
     // We add prefix, since #tree == FALSE.
     $element['workflow']['workflow_entity'] = array('#type' => 'value', '#value' => $this->entity);
     $element['workflow']['workflow_entity_type'] = array('#type' => 'value', '#value' => $this->entity_type);
     $element['workflow']['workflow_field'] = array('#type' => 'value', '#value' => $this->field);
     $element['workflow']['workflow_instance'] = array('#type' => 'value', '#value' => $this->instance);
     // Save the form_id, so the form values can be retrieved in submit function.
     $element['workflow']['form_id'] = array('#type' => 'value', '#value' => $form_id);
     // First of all, we add the default value in the place were normal fields
     // have it. This is to cater for 'preview' of the entity.
     $element['#default_value'] = $default_value;
     // Decide if we show a widget or a formatter.
     // There is no need to a widget when the only choice is the current sid.
     if (!$current_state->showWidget($options)) {
         $element['workflow'][$element_options_name] = workflow_state_formatter($entity_type, $entity, $field, $instance);
         return $element;
     } else {
         $element['workflow'][$element_options_name] = array('#type' => $this->field['settings']['widget']['options'], '#title' => $settings_title_as_name ? t('Change !name state', array('!name' => $label)) : '', '#options' => $options, '#default_value' => $default_value);
     }
     // Display scheduling form, but only if entity is being edited and user has
     // permission. State change cannot be scheduled at entity creation because
     // that leaves the entity in the (creation) state.
     if ($settings_schedule == TRUE && user_access('schedule workflow transitions')) {
         global $user;
         if (variable_get('configurable_timezones', 1) && $user->uid && drupal_strlen($user->timezone)) {
             $timezone = $user->timezone;
         } else {
             $timezone = variable_get('date_default_timezone', 0);
         }
         $timezones = drupal_map_assoc(timezone_identifiers_list());
         $hours = format_date($timestamp, 'custom', 'H:i', $timezone);
         //      $element['workflow']['workflow_scheduled'] = array(
         $element['workflow'][$element_scheduled_name] = array('#type' => 'radios', '#title' => t('Schedule'), '#options' => array('0' => t('Immediately'), '1' => t('Schedule for state change')), '#default_value' => $scheduled, '#attributes' => array('id' => 'scheduled_' . $form_id));
         $element['workflow']['workflow_scheduled_date_time'] = array('#type' => 'fieldset', '#title' => t('At'), '#attributes' => array('class' => array('container-inline')), '#prefix' => '<div style="margin-left: 1em;">', '#suffix' => '</div>', '#states' => array('visible' => array(':input[id="' . 'scheduled_' . $form_id . '"]' => array('value' => '1'))));
         $element['workflow']['workflow_scheduled_date_time']['workflow_scheduled_date'] = array('#type' => 'date', '#default_value' => array('day' => date('j', $timestamp), 'month' => date('n', $timestamp), 'year' => date('Y', $timestamp)));
         $element['workflow']['workflow_scheduled_date_time']['workflow_scheduled_hour'] = array('#type' => 'textfield', '#title' => t('Time'), '#maxlength' => 5, '#size' => 6, '#default_value' => $scheduled ? $hours : '00:00');
         $element['workflow']['workflow_scheduled_date_time']['workflow_scheduled_timezone'] = array('#type' => $settings_schedule_timezone ? 'select' : 'hidden', '#title' => t('Time zone'), '#options' => $timezones, '#default_value' => array($timezone => $timezone));
         $element['workflow']['workflow_scheduled_date_time']['workflow_scheduled_help'] = array('#type' => 'item', '#prefix' => '<br />', '#description' => t('Please enter a time in 24 hour (eg. HH:MM) format.
       If no time is included, the default will be midnight on the specified date.
       The current time is: @time.', array('@time' => format_date(REQUEST_TIME, 'custom', 'H:i', $timezone))));
     }
     $element['workflow']['workflow_comment'] = array('#type' => $settings_comment, '#title' => t('Workflow comment'), '#description' => t('A comment to put in the workflow log.'), '#default_value' => $comment, '#rows' => 2);
     // The 'add submit' can explicitely set by workflowfield_field_formatter_view(),
     // to add the submit button on the Content view page and the Workflow history tab.
     if (!empty($this->instance['widget']['settings']['submit_function'])) {
         // Add a submit button, but only on Entity View and History page.
         $element['workflow']['submit'] = array('#type' => 'submit', '#value' => t('Update workflow'), '#executes_submit_callback' => TRUE, '#submit' => array($this->instance['widget']['settings']['submit_function']));
     }
     return $element;
 }
Ejemplo n.º 30
0
/**
 *
 * @param $value
 * @param int $length
 * @param bool $elipse
 * @param bool $words
 * @return string
 */
function tfd_truncate_text($value, $length = 300, $elipse = TRUE, $words = TRUE)
{
    $value = tfd_render($value);
    if (drupal_strlen($value) > $length) {
        $value = drupal_substr($value, 0, $length);
        if ($words) {
            $regex = "(.*)\\b.+";
            if (function_exists('mb_ereg')) {
                mb_regex_encoding('UTF-8');
                $found = mb_ereg($regex, $value, $matches);
            } else {
                $found = preg_match("/{$regex}/us", $value, $matches);
            }
            if ($found) {
                $value = $matches[1];
            }
        }
        // Remove scraps of HTML entities from the end of a strings
        $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));
        if ($elipse) {
            $value .= ' ' . t('...');
        }
    }
    return $value;
}