Callback used when generating a shortname based on a template.

@param string $fullname full name.
@param string $idnumber ID number.
@param array $block result from preg_replace_callback.
@return string
182766
public static function generate_shortname_callback($fullname, $idnumber, $block) {
        switch ($block[3]) {
            case 'f':
                $repl = $fullname;
                break;
            case 'i':
                $repl = $idnumber;
                break;
            default:
                return $block[0];
        }

        switch ($block[1]) {
            case '+':
                $repl = core_text::strtoupper($repl);
                break;
            case '-':
                $repl = core_text::strtolower($repl);
                break;
            case '~':
                $repl = core_text::strtotitle($repl);
                break;
        }

        if (!empty($block[2])) {
            $repl = core_text::substr($repl, 0, $block[2]);
        }

        return $repl;
    }
1214570
public function getContentIdByBlockId($id)
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->select($this->connection->quoteIdentifier('contentobject_id'))
            ->from($this->connection->quoteIdentifier('ezcontentobject_tree'), 't')
            ->innerJoin(
                't',
                $this->connection->quoteIdentifier(self::EZM_BLOCK_TABLE),
                'b',
                $query->expr()->eq(
                    $this->connection->quoteIdentifier('b.node_id'),
                    $this->connection->quoteIdentifier('t.node_id')
                )
            )
            ->where(
                $query->expr()->eq($this->connection->quoteIdentifier('b.id'), ':id')
            )
            ->setParameter(':id', $id, PDO::PARAM_STR)
        ;

        $statement = $query->execute();

        $contentId = $statement->fetchColumn();
        if ($contentId === false) {
            throw new NotFoundException('Block', $id);
        }

        return $contentId;
    }
865248
public static function mkname($full, $tail, $fsencoding = '') {
        $full = self::conv_to($full, $fsencoding);
        $name = '';
        $count = 0;
        $now = time();
        $time = date('YmdHis', $now);
        $year = date('Y', $now);
        $month_day = date('md', $now);
        while ($name == '' && $count < 100) {
            $rand = rand(100000, 999999);
            $name = $year . '/' . $month_day . '/' . $time . $rand . $tail;
            if (file_exists($full . '/' . $name)) {
                $name = '';
            }
            $count++;
        }
        return $name;
    }
1191566
public function stripPadding($block, $data) {
    $pad = ord($data[($len = strlen($data)) - 1]);

    /* Check that what we have at the end of the string really is padding, and if it is remove it. */
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $data)) {
      return substr($data, 0, -$pad);
    }
    return $data;
  }
384382
protected function buildCallParentMethodCode($fullClassName, $methodName)
    {
        if (!$this->reflectionService->hasMethod($fullClassName, $methodName)) {
            return '';
        }
        if (count($this->reflectionService->getMethodParameters($this->fullOriginalClassName, $this->methodName)) > 0) {
            return "        call_user_func_array('parent::" . $methodName . "', \$arguments);\n";
        } else {
            return "        parent::" . $methodName . "();\n";
        }
    }
609468
public function callBlock(string $block = '', ...$params): ?string
    {
        /** @var ModuleBlockInterface|null $module */
        $module = $this->module_service
            ->findByComponent(ModuleBlockInterface::class, $this->tree, Auth::user())
            ->first(static function (ModuleInterface $module) use ($block): bool {
                return $module->name() === $block && $module->name() !== 'html';
            });

        if ($module === null) {
            return '';
        }

        // Build the config array
        $cfg = [];
        foreach ($params as $config) {
            $bits = explode('=', $config);

            if (count($bits) < 2) {
                continue;
            }

            $v       = array_shift($bits);
            $cfg[$v] = implode('=', $bits);
        }

        return $module->getBlock($this->tree, 0, '', $cfg);
    }
1179758
protected function renderRawHtml($block)
	{
        $output = $block['content'];
        if (is_callable($this->rawHtmlFilter, true)) {
            $output = call_user_func($this->rawHtmlFilter, $output);
        }
		return $output . "\n";
	}
57935
private function generateClassName($fullClassName)
    {
        $namespace = $this->getClassNamespace($fullClassName);

        $className = $fullClassName;

        if ($namespace) {
            $className = substr($fullClassName, strrpos($fullClassName, '\\') + 1, strlen($fullClassName));
        }

        return $className;
    }
85309
public function generate(string $fullName, \DateTimeInterface $birthday, int $characterLimit = 8, int $maxUsernamePerPrefix = 1000)
    {
        $fullName = strtoupper($fullName);
        $characters = array();
        $isShort = false;

        if ($characterLimit > strlen($fullName)) {
            $shortGenerator = new ShortUsernameGenerator();
            $characters = array_merge($characters, $shortGenerator->generate($fullName, $characterLimit));

            $isShort = true;
        }

        if (!$isShort) {
            $characters = $this->doGenerate($fullName, $characterLimit, $characters);
        }

        $realUsername = $this->getUsername($birthday, $characters, $maxUsernamePerPrefix);

        if ($this->autoSave) {
            $this->save($birthday, $fullName, $realUsername);
        }

        return $realUsername;
    }
1055988
private function findBlockById(BlockView $blockView, $id)
    {
        foreach ($blockView->children as $childView) {
            if ($childView->getId() === $id) {
                return $childView;
            }

            $childView = $this->findBlockById($childView, $id);
            if ($childView) {
                return $childView;
            }
        }

        return null;
    }
1347046
protected function getUri($id = 0, $fulluri = true, $slugfield = 'slug')
    {
        $title = $this->getTitle();
        $contenttype = $this->getContenttype();
        $repo = $this->app['storage']->getRepository($contenttype);
        $tablename = $repo->getTableName();
        $id = intval($id);
        $slug = $this->app['slugify']->slugify($title);

        // Don't allow strictly numeric slugs, unless allow_numeric_slugs options is set
        if (is_numeric($slug) && $contenttype['allow_numeric_slugs'] !== true) {
            $slug = $contenttype['singular_slug'] . "-" . $slug;
        }

        // Only add '{contenttype}/' if $full is requested.
        if ($fulluri) {
            $prefix = '/' . $contenttype['singular_slug'] . '/';
        } else {
            $prefix = '';
        }

        //check if the fieldname exists, otherwise use 'slug' as fallback
        if (!in_array($slugfield, array_keys($contenttype['fields']))) {
            $slugfield = 'slug';
        }

        $query = sprintf(
            "SELECT id from %s WHERE %s=? and id!=?",
            $tablename,
            $slugfield
        );

        $res = $this->app['db']->executeQuery(
            $query,
            [$slug, $id],
            [\PDO::PARAM_STR, \PDO::PARAM_INT]
        )->fetch();

        if (!$res) {
            $uri = $prefix . $slug;
        } else {
            for ($i = 1; $i <= 10; $i++) {
                $newslug = Html::trimText($slug, 127 - strlen($i), false) . '-' . $i;
                $res = $this->app['db']->executeQuery(
                    $query,
                    [$newslug, $id],
                    [\PDO::PARAM_STR, \PDO::PARAM_INT]
                )->fetch();
                if (!$res) {
                    $uri = $prefix . $newslug;
                    break;
                }
            }

            // otherwise, just get a random slug.
            if (empty($uri)) {
                $suffix = '-' . $this->app['randomgenerator']->generateString(6, 'abcdefghijklmnopqrstuvwxyz01234567890');
                $slug = Html::trimText($slug, 128 - strlen($suffix), false) . $suffix;
                $uri = $prefix . $slug;
            }
        }

        return $uri;
    }
1069151
public String getFullName() {
	String fullName;
	if (tagLib != null) {
	    fullName = tagLib.getNameSpaceAndSeparator() + name;
	}
	else {
	    fullName = name;
	}
	return fullName;
    }
970669
private function doGenerate($fullName, $characterLimit, array $characters = array())
    {
        $balineseGenerator = new BalinesePetrukUsername();
        if (-1 !== $balineseGenerator->isReservedName($fullName)) {
            $characters = array_merge($characters, $balineseGenerator->generate($fullName, $characterLimit));
        }

        $islamicGenerator = new IslamicPetrukUsername();
        if (-1 !== $islamicGenerator->isReservedName($fullName)) {
            $characters = array_merge($characters, $islamicGenerator->generate($fullName, $characterLimit));
        }

        $westernGenerator = new WesternPetrukUsername();
        if (-1 !== $westernGenerator->isReservedName($fullName)) {
            $characters = array_merge($characters, $westernGenerator->generate($fullName, $characterLimit));
        }

        $genericGenerator = new GenericPetrukUsername();
        $characters = array_merge($characters, $genericGenerator->generate($fullName, $characterLimit));

        return $characters;
    }
1328076
protected function generateBlockXmlString(Parts\Block $block, DOMDocument $dom)
    {
        $blockNode = $dom->createElement('block');

        foreach ($block->getState() as $attrName => $attrValue) {
            switch ($attrName) {
                case 'id':
                    $blockNode->setAttribute('id', 'id_' . $attrValue);
                    break;
                case 'zoneId':
                    $blockNode->appendChild($dom->createElement('zone_id', $attrValue));
                    break;
                case 'action':
                    if ($attrValue !== null) {
                        $blockNode->setAttribute('action', $attrValue);
                    }
                    break;
                case 'items':
                    foreach ($block->items as $item) {
                        $itemNode = $this->generateItemXmlString($item, $dom);
                        if ($itemNode) {
                            $blockNode->appendChild($itemNode);
                        }
                    }
                    break;
                case 'overflowId':
                    $this->addNewXmlElement($dom, $blockNode, 'overflow_id', $attrValue);
                    break;
                case 'rotation':
                    if ($attrValue === null) {
                        continue 2;
                    }

                    $node = $dom->createElement($attrName);
                    $blockNode->appendChild($node);

                    foreach ($attrValue as $arrayItemKey => $arrayItemValue) {
                        $this->addNewXmlElement($dom, $node, $arrayItemKey, $arrayItemValue);
                    }
                    break;
                case 'customAttributes':
                    if ($attrValue === null) {
                        continue 2;
                    }

                    $node = $dom->createElement('custom_attributes');
                    $blockNode->appendChild($node);

                    foreach ($attrValue as $arrayItemKey => $arrayItemValue) {
                        $this->addNewXmlElement($dom, $node, $arrayItemKey, $arrayItemValue);
                    }
                    break;
                case 'attributes':
                    foreach ($attrValue as $arrayItemKey => $arrayItemValue) {
                        $this->addNewXmlElement($dom, $blockNode, $arrayItemKey, $arrayItemValue);
                    }
                    break;
                default:
                    $this->addNewNotEmptyXmlElement($dom, $blockNode, $attrName, $attrValue);
                    break;
            }
        }

        return $blockNode;
    }
99120
public static function generate_shortname($data, $templateshortname) {
        if (empty($templateshortname) && !is_numeric($templateshortname)) {
            return null;
        }
        if (strpos($templateshortname, '%') === false) {
            return $templateshortname;
        }

        $course = (object) $data;
        $fullname   = isset($course->fullname) ? $course->fullname : '';
        $idnumber   = isset($course->idnumber) ? $course->idnumber  : '';

        $callback = partial(array('tool_uploadcourse_helper', 'generate_shortname_callback'), $fullname, $idnumber);
        $result = preg_replace_callback('/(?<!%)%([+~-])?(\d)*([fi])/', $callback, $templateshortname);

        if (!is_null($result)) {
            $result = clean_param($result, PARAM_TEXT);
        }

        if (empty($result) && !is_numeric($result)) {
            $result = null;
        }

        return $result;
    }
1221868
public static function parse_name($full_name) {
    # Remove leading/trailing whitespace
    $full_name = trim($full_name);
    # Setup default vars
    extract(array('salutation' => '', 'fname' => '', 'initials' => '', 'lname' => '', 'suffix' => ''));
    # If name contains professional suffix, assign and remove it
    $professional_suffix = self::get_pro_suffix($full_name);
    if ($professional_suffix) {
      # Remove the suffix from full name
      $full_name = str_replace($professional_suffix, '', $full_name);
      # Remove the preceeding comma and space(s) from suffix
      $professional_suffix = preg_replace("/, */", '', $professional_suffix);
      # Normalize the case of suffix if found in dictionary
      foreach (self::$dict['suffixes']['prof'] as $prosuffix) {
        if (strtolower($prosuffix) === strtolower($professional_suffix)) {
          $professional_suffix = $prosuffix;
        }
      }
    }
    # Deal with nickname, push to array
    $has_nick = self::get_nickname($full_name);
    if ($has_nick) {
      # Remove wrapper chars from around nickname
      $name['nickname'] = substr($has_nick, 1, (strlen($has_nick) - 2));
      # Remove the nickname from the full name
      $full_name = str_replace($has_nick, '', $full_name);
      # Get rid of consecutive spaces left by the removal
      $full_name = str_replace('  ', ' ', $full_name);
    }
    # Grab a list of words from name
    $unfiltered_name_parts = self::break_words($full_name);
    # Is first word a title or multiple titles consecutively?
    while ($s = self::is_salutation($unfiltered_name_parts[0])) {
      $salutation .= "$s ";
      array_shift($unfiltered_name_parts);
    }
    $salutation = trim($salutation);
    # Is last word a suffix or multiple suffixes consecutively?
    while ($s = self::is_suffix($unfiltered_name_parts[count($unfiltered_name_parts)-1], $full_name)) {
      $suffix .= "$s ";
      array_pop($unfiltered_name_parts);
    }
    $suffix = trim($suffix);
    # If suffix and professional suffix not empty, add comma
    if (!empty($professional_suffix) && !empty($suffix)) {
      $suffix .= ', ';
    }
    # Concat professional suffix to suffix
    $suffix .= $professional_suffix;
    # set the ending range after prefix/suffix trim
    $end = count($unfiltered_name_parts);
    # concat the first name
    for ($i=0; $i<$end-1; $i++) {
      $word = $unfiltered_name_parts[$i];
      # move on to parsing the last name if we find an indicator of a compound last name (Von, Van, etc)
      # we use $i != 0 to allow for rare cases where an indicator is actually the first name (like "Von Fabella")
      if (self::is_compound($word) && $i != 0) {
        break;
      }
      # is it a middle initial or part of their first name?
      # if we start off with an initial, we'll call it the first name
      if (self::is_initial($word)) {
        # is the initial the first word?
        if ($i == 0) {
          # if so, do a look-ahead to see if they go by their middle name
          # for ex: "R. Jason Smith" => "Jason Smith" & "R." is stored as an initial
          # but "R. J. Smith" => "R. Smith" and "J." is stored as an initial
          if (self::is_initial($unfiltered_name_parts[$i+1])) {
            $fname .= " ".strtoupper($word);
          }
          else {
            $initials .= " ".strtoupper($word);
          }
        }
        # otherwise, just go ahead and save the initial
        else {
          $initials .= " ".strtoupper($word);
        }
      }
      else {
        $fname .= " ".self::fix_case($word);
      }
    }
    # check that we have more than 1 word in our string
    if ($end-0 > 1) {
      # concat the last name
      for ($i; $i < $end; $i++) {
        $lname .= " ".self::fix_case($unfiltered_name_parts[$i]);
      }
    }
    else {
      # otherwise, single word strings are assumed to be first names
      $fname = self::fix_case($unfiltered_name_parts[$i]);
    }
    # return the various parts in an array
    $name['salutation'] = $salutation;
    $name['fname'] = trim($fname);
    $name['initials'] = trim($initials);
    $name['lname'] = trim($lname);
    $name['suffix'] = $suffix;
    return $name;
  }
1370608
public function getPeopleIdFromFullName($fullName) {
        $result = DB::table('peoples')
            ->where('first_name',  $this->getFirstName($fullName))
            ->where('middle_name', $this->getMiddleName($fullName))
            ->where('surname',     $this->getLastName($fullName))
            ->first()
        ;

        if (count($result) > 0) {
            return $result->id;
        }
        return 0;
    }