You are here

function _gotwo_get in Go - url redirects 7

Same name and namespace in other branches
  1. 6 gotwo.module \_gotwo_get()

Return the GO object url for a given link.

2 calls to _gotwo_get()
gotwo_add_form_submit in ./gotwo.admin.inc
Go redirect has been submitted.
_gotwo_get_url in ./gotwo.module
Return the GO url for a given link.

File

./gotwo.module, line 324
Module that provides easy to use redirection links. A redirection link would be like: http://examples.org/go/a_label http://examples.org/go/123546 http://examples.org/go/or/like/this

Code

function _gotwo_get($url, $src = NULL, $flags = GOTWO_CREATE) {

  // Only add valid URLs to the database. Otherwise the disclaimer reload may fail.
  if (!valid_url($url)) {
    return FALSE;
  }

  // If there is no title to mangle, use the url without schema instead.
  if (!$src) {
    $src = preg_replace('#^(http(s)?://)#', '', $url);
  }
  $src = _gotwo_cleanstring($src);
  $maxlength = variable_get('gotwo_max_length', 128);
  $res = db_query("SELECT * FROM {gotwo} WHERE src = :src AND dst = :dst", array(
    ':src' => $src,
    ':dst' => $url,
  ))
    ->fetchObject();
  if ($res === FALSE) {
    $res = db_query("SELECT * FROM {gotwo} WHERE src = gid+:src AND dst = :dst", array(
      ':src' => '/' . $src,
      ':dst' => $url,
    ))
      ->fetchObject();
    if (!empty($res)) {
      $src_old = substr($res->gid . '/' . $src, 0, $maxlength);
      if ($src_old != $res->src) {
        $res == FALSE;
      }
    }
  }
  if ($res === FALSE) {
    $res = new stdClass();
    if ($flags & GOTWO_CREATE) {

      // Force unique src.
      $res = db_query("SELECT * FROM {gotwo} WHERE src = :src", array(
        ':src' => $src,
      ))
        ->fetchObject();
      if (!empty($res)) {

        // TODO: find a better solution.
        // Insert a dummy first with an uniqe src value to get the 'gid' value.
        $gid = db_insert('gotwo')
          ->fields(array(
          'src' => uniqid(),
          'dst' => $url,
        ))
          ->execute();
        $src = substr($gid . '/' . $src, 0, $maxlength);
        db_update('gotwo')
          ->fields(array(
          'src' => $src,
        ))
          ->condition('gid', $gid)
          ->execute();
        $res->gid = $gid;
        $res->src = $src;
        $res->dst = $url;
      }
      else {
        $gid = db_insert('gotwo')
          ->fields(array(
          'src' => $src,
          'dst' => $url,
        ))
          ->execute();
        $res->gid = $gid;
        $res->src = $src;
        $res->dst = $url;
      }
    }
    else {
      return FALSE;
    }
  }
  return $res;
}