public function validate($dataspace)
  {
    if(!$value = $dataspace->get($this->field_name))
      return;

    $tree = Limb :: toolkit()->getTree();

    if(!$tree->isNode($this->parent_node_id))
      return;

    if(!$nodes = $tree->getChildren($this->parent_node_id))
      return;

    foreach($nodes as $id => $node)
    {
      if($node['identifier'] != $value)
        continue;

      if($this->node_id == self :: UNKNOWN_NODE_ID)
      {
        $this->error(Strings :: get('error_duplicate_tree_identifier', 'error'));
        break;
      }
      elseif($id != $this->node_id)
      {
        $this->error(Strings :: get('error_duplicate_tree_identifier', 'error'));
        break;
      }
    }
  }
Esempio n. 2
0
 public function searchAction()
 {
     try {
         $tableName = $this->request->getPost('table');
         $field = $this->request->getPost('field');
         $search = $this->request->getPost('search');
         $modelName = Strings::tableNameToModelName($tableName);
         $results = array();
         if (class_exists($modelName)) {
             $pri = $modelName::primaryKeyName();
             $condition = '';
             if ($field) {
                 if ($search) {
                     $condition = "{$field} LIKE '%{$search}%'";
                     if (is_numeric($search)) {
                         $condition .= " or {$pri}={$search}";
                     }
                     $results = $modelName::find(array('conditions' => $condition, "limit" => 20));
                     $results = $results->toArray();
                 }
             }
             // TODO: Merge two parts
             parent::result(array('results' => $results, 'SQL' => $condition, 'key' => $pri));
         } else {
             parent::error(-2, "{$modelName} does not exists");
         }
     } catch (Exception $e) {
         parent::error(-3, "{$e}");
     }
     parent::error(-1, "{$modelName} ?");
 }
  public function validate($dataspace)
  {
    $value = $dataspace->get($this->field_name);

    if(!Limb :: toolkit()->getTree()->getNodeByPath($value))
      $this->error(Strings :: get('error_invalid_tree_path', 'error'));
  }
Esempio n. 4
0
 /**
  * Get temporary filename
  */
 public static function getTempFilePath($parentDirectory, $extension = '')
 {
     do {
         $tmpPath = $parentDirectory . '/' . Strings::createRandomString(null, Strings::ALPHABET_ALPHANUMERICAL_LOWCASE, 64) . ($extension == '' ? '' : '.' . $extension);
     } while (file_exists($tmpPath));
     return $tmpPath;
 }
Esempio n. 5
0
 /**
  * Generate a path to the mercurial repo for the file
  *
  * @param  string $locale locale code
  * @param  string $repo   repository name
  * @param  string $path   Entity name representing the local file
  * @return string Path to the file in remote mercurial repository
  */
 public static function hgPath($locale, $repo, $path)
 {
     $url = 'https://hg.mozilla.org';
     // remove entity from path and store it in a variable
     $path = explode(':', $path);
     $path = $path[0];
     $path = explode('/', $path);
     $entity_file = array_pop($path);
     $path = implode('/', $path);
     $exploded_path = explode('/', $path);
     $base_folder = $exploded_path[0];
     if (Strings::startsWith($repo, 'gaia') || in_array($base_folder, ['apps', 'shared', 'showcase_apps', 'test_apps', 'test_external_apps'])) {
         $locale = Project::getLocaleInContext($locale, $repo);
         if ($repo == 'gaia') {
             $url .= '/gaia-l10n/' . $locale . '/file/default/';
         } else {
             $version = str_replace('gaia_', '', $repo);
             $url .= '/releases/gaia-l10n/v' . $version . '/' . $locale . '/file/default/';
         }
         return $url . $path . '/' . $entity_file;
     }
     $en_US_Folder_Mess = ['b2g/branding/official/', 'b2g/branding/unofficial/', 'b2g/', 'netwerk/', 'embedding/android/', 'testing/extensions/community/chrome/', 'intl/', 'extensions/spellcheck/', 'services/sync/', 'mobile/android/branding/aurora/', 'mobile/android/branding/official/', 'mobile/android/branding/nightly/', 'mobile/android/branding/unofficial/', 'mobile/android/branding/beta/', 'mobile/android/base/', 'mobile/android/', 'mobile/', 'security/manager/', 'toolkit/content/tests/fennec-tile-testapp/chrome/', 'toolkit/', 'browser/branding/aurora/', 'browser/branding/official/', 'browser/branding/nightly/', 'browser/branding/unofficial/', 'browser/', 'devtools/client/', 'devtools/shared/', 'layout/tools/layout-debug/ui/', 'dom/', 'webapprt/', 'chat/', 'suite/', 'other-licenses/branding/thunderbird/', 'mail/branding/aurora/', 'mail/branding/nightly/', 'mail/', 'mail/test/resources/mozmill/mozmill/extension/', 'editor/ui/', 'calendar/'];
     // Destop repos
     if ($locale != 'en-US') {
         if ($repo == 'central') {
             $url .= '/l10n-central/' . $locale . '/file/default/';
         } else {
             $url .= '/releases/l10n/mozilla-' . $repo . '/' . $locale . '/file/default/';
         }
     } else {
         if (in_array($base_folder, ['calendar', 'chat', 'editor', 'ldap', 'mail', 'mailnews', 'suite'])) {
             $repo_base = 'comm';
         } else {
             $repo_base = 'mozilla';
         }
         if ($repo == 'central') {
             $url .= "/{$repo_base}-central/file/default/";
         } else {
             $url .= "/releases/{$repo_base}-{$repo}/file/default/";
         }
         $loop = true;
         while ($loop && count($exploded_path) > 0) {
             if (in_array(implode('/', $exploded_path) . '/', $en_US_Folder_Mess)) {
                 $path_part1 = implode('/', $exploded_path) . '/locales/en-US';
                 $pattern = preg_quote(implode('/', $exploded_path), '/');
                 $path = preg_replace('/' . $pattern . '/', $path_part1, $path, 1);
                 $loop = false;
                 break;
             } else {
                 array_pop($exploded_path);
             }
         }
         if ($loop == true) {
             $path = explode('/', $path);
             $category = array_shift($path);
             $path = $category . '/locales/en-US/' . implode('/', $path);
         }
     }
     return $url . $path . '/' . $entity_file;
 }
  static function instance()
  {
    if (!self :: $_instance)
      self :: $_instance = new Strings();

    return self :: $_instance;
  }
 public function process(array $documents, &$context)
 {
     $doc = $documents[self::URL_HISTORY];
     $dom = self::getDOM($doc);
     $xpath = new DOMXPath($dom);
     Database::delete('userhistory', ['user_id' => $context->user->id]);
     $data = [];
     $nodes = $xpath->query('//table//td[@class = \'borderClass\']/..');
     foreach ($nodes as $node) {
         //basic info
         $link = $node->childNodes->item(0)->childNodes->item(0)->getAttribute('href');
         preg_match('/(\\d+)\\/?$/', $link, $matches);
         $media = strpos($link, 'manga') !== false ? Media::Manga : Media::Anime;
         $mediaMalId = intval($matches[0]);
         $progress = Strings::makeInteger($node->childNodes->item(0)->childNodes->item(2)->nodeValue);
         //parse time
         //That's what MAL servers output for MG client
         if (isset($doc->headers['Date'])) {
             date_default_timezone_set('UTC');
             $now = strtotime($doc->headers['Date']);
         } else {
             $now = time();
         }
         date_default_timezone_set('America/Los_Angeles');
         $hour = date('H', $now);
         $minute = date('i', $now);
         $second = date('s', $now);
         $day = date('d', $now);
         $month = date('m', $now);
         $year = date('Y', $now);
         $dateString = $node->childNodes->item(2)->nodeValue;
         if (preg_match('/(\\d*) seconds? ago/', $dateString, $matches)) {
             $second -= intval($matches[1]);
         } elseif (preg_match('/(\\d*) minutes? ago/', $dateString, $matches)) {
             $second -= intval($matches[1]) * 60;
         } elseif (preg_match('/(\\d*) hours? ago/', $dateString, $matches)) {
             $minute -= intval($matches[1]) * 60;
         } elseif (preg_match('/Today, (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
         } elseif (preg_match('/Yesterday, (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
             $hour -= 24;
         } elseif (preg_match('/(\\d\\d)-(\\d\\d)-(\\d\\d), (\\d*):(\\d\\d) (AM|PM)/', $dateString, $matches)) {
             $year = intval($matches[3]) + 2000;
             $month = intval($matches[1]);
             $day = intval($matches[2]);
             $hour = intval($matches[4]);
             $minute = intval($matches[5]);
             $hour += ($matches[6] == 'PM' and $hour != 12) ? 12 : 0;
         }
         $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
         date_default_timezone_set('UTC');
         $data[] = ['user_id' => $context->user->id, 'mal_id' => $mediaMalId, 'media' => $media, 'progress' => $progress, 'timestamp' => date('Y-m-d H:i:s', $timestamp)];
     }
     Database::insert('userhistory', $data);
 }
Esempio n. 8
0
 public function testToCamel()
 {
     $tests = array('start_middle_last' => 'startMiddleLast', 'simple_xml' => 'simpleXml', 'pdf_load' => 'pdfLoad', 'simple_test' => 'simpleTest', 'easy' => 'easy', 'html' => 'html', 'a_string' => 'aString', 'some4_numbers234' => 'some4Numbers234', 'test123_string' => 'test123String');
     foreach ($tests as $value => $expeted) {
         $this->assertSame($expeted, Strings::toCamel($value));
     }
 }
Esempio n. 9
0
 /**
  *
  * Loads strings from a .lang file into an array. File format is:
  *  ;String in english
  *  translated string
  *
  * @param  string  $file             .lang file to load
  * @param  boolean $reference_locale True if the current locale is the reference locale
  * @return array   Array of strings as [original => translation]
  */
 public static function getStrings($file, $reference_locale)
 {
     // get all the lines in an array
     $f = self::getFile($file);
     $strings = [];
     for ($i = 0, $lines = count($f); $i < $lines; $i++) {
         // skip comments and metadata
         if (Strings::startsWith($f[$i], '#')) {
             continue;
         }
         if (Strings::startsWith($f[$i], ';') && !empty($f[$i + 1])) {
             $english = trim(substr($f[$i], 1));
             if (Strings::startsWith($f[$i + 1], '#') || Strings::startsWith($f[$i + 1], ';')) {
                 /* String is not translated, next line is a comment or
                  * the next source string. I consider the string untranslated
                  */
                 $translation = $english;
             } else {
                 // Next line is an actual translation
                 $translation = trim($f[$i + 1]);
             }
             // If untranslated, I need to store an empty string as translation
             // unless it's the reference locale
             if ($reference_locale) {
                 $strings[$english] = $english;
             } else {
                 $strings[$english] = $translation == $english ? '' : $translation;
             }
             $i++;
         }
     }
     return $strings;
 }
Esempio n. 10
0
 public function process(array $documents, &$context)
 {
     $doc = $documents[self::URL_MEDIA];
     $dom = self::getDOM($doc);
     $xpath = new DOMXPath($dom);
     //chapter count
     preg_match_all('#([0-9]+|Unknown)#', self::getNodeValue($xpath, '//span[text() = \'Chapters:\']/following-sibling::node()[self::text()]'), $matches);
     $chapterCount = Strings::makeInteger($matches[0][0]);
     //volume count
     preg_match_all('#([0-9]+|Unknown)#', self::getNodeValue($xpath, '//span[text() = \'Volumes:\']/following-sibling::node()[self::text()]'), $matches);
     $volumeCount = Strings::makeInteger($matches[0][0]);
     //serialization
     $serializationMalId = null;
     $serializationName = null;
     $q = $xpath->query('//span[text() = \'Serialization:\']/../a');
     if ($q->length > 0) {
         $node = $q->item(0);
         preg_match('#/magazine/([0-9]+)$#', $node->getAttribute('href'), $matches);
         $serializationMalId = Strings::makeInteger($matches[1]);
         $serializationName = Strings::removeSpaces($q->item(0)->nodeValue);
     }
     $media =& $context->media;
     $media->chapters = $chapterCount;
     $media->volumes = $volumeCount;
     $media->serialization_id = $serializationMalId;
     $media->serialization_name = $serializationName;
     R::store($media);
 }
  function testGetActions()
  {
    $j = new ActionsComponent();

    $actions = array(
      'display' => array(),
      'edit' => array(
          'JIP' => false,
          'action_name' => Strings :: get('edit'),
          'img_src' => '/shared/images/edit.gif',
      ),
      'delete' => array(
          'JIP' => true,
          'action_name' => Strings :: get('delete'),
          'img_src' => '/shared/images/rem.gif',
      ),
    );

    $j->setActions($actions);
    $j->setNodeId(100);

    $actions = $j->getActions();

    $this->assertTrue(is_array($actions));
    $this->assertEqual(count($actions), 1);

    $action = reset($actions);
    $this->assertEqual($action['action'], 'delete');

    $this->assertWantedPattern('/^\/root\?.+$/', $action['action_href']);
    $this->assertWantedPattern('/&*action=delete/', $action['action_href']);
    $this->assertWantedPattern('/&*node_id=100/', $action['action_href']);
  }
Esempio n. 12
0
 /**
  * Filter: removes unnecessary whitespace and shortens value to control's max length.
  * @return string
  */
 public function sanitize($value)
 {
     if ($this->control->maxlength && Strings::length($value) > $this->control->maxlength) {
         $value = Strings::substring($value, 0, $this->control->maxlength);
     }
     return Strings::trim(strtr($value, "\r\n", '  '));
 }
 protected function check($value)
 {
   if(empty($value))
     $this->error(Strings :: get('error_invalid_tree_node_id', 'error'));
   elseif(!Limb :: toolkit()->getTree()->getNode((int)$value))
     $this->error(Strings :: get('error_invalid_tree_node_id', 'error'));
 }
Esempio n. 14
0
 public static function allow_page_edit($presenter, $id)
 {
     if (!$presenter->user->isInRole('user')) {
         //probably admin -> allow
         return true;
     }
     //log all changes by users
     if (count($presenter->request->post)) {
         $v = PagesModel::getPageById($id);
     } else {
         $v = $presenter->request;
     }
     $key = Strings::webalize($presenter->user->id);
     $data = date("Y-m-d H:i:s ") . $_SERVER["REQUEST_URI"] . " " . base64_encode(print_r($v, 1));
     file_put_contents(WWW_DIR . "/data/activitylog/{$key}.log", $data, FILE_APPEND);
     if ($presenter->user->identity->webpages == 'all') {
         return true;
     }
     $allowed = explode(',', $presenter->user->identity->webpages);
     foreach (PagesModel::getPageById($id)->getParents() as $page) {
         if (in_array($page->id, $allowed)) {
             //allowed to edit page?
             return true;
         }
     }
     return false;
 }
  public function prepare()
  {
    $params = array();
    $params['id'] = $this->get('node_id');
    $params['action'] = 'order';
    $params['rn'] = time();
    $params['popup'] = 1;

    $this->set('order_up_alt', Strings :: get('order_up'));
    $this->set('order_down_alt', Strings :: get('order_down'));

    if (!$this->get('is_first_child'))
    {
      $params['direction'] = 'up';
      $this->set('order_up_href', addUrlQueryItems($_SERVER['PHP_SELF'], $params));
    }
    else
      $this->set('order_up_href', '');

    if (!$this->get('is_last_child'))
    {
      $params['direction'] = 'down';
      $this->set('order_down_href', addUrlQueryItems($_SERVER['PHP_SELF'], $params));
    }
    else
      $this->set('order_down_href', '');

    return parent :: prepare();
  }
Esempio n. 16
0
File: db.php Progetto: demental/m
 public function create_guid($obj)
 {
     if (!$obj->pk()) {
         $obj->{$obj->pkName()} = Strings::create_guid();
         $obj->__new_with_id = 1;
     }
 }
 protected function _validPerform($request, $response)
 {
     $mail_data = $this->dataspace->export();
     if (isset($mail_data['sender_name'])) {
         $sender_name = $mail_data['sender_name'];
     } else {
         $sender_name = $mail_data['sender_firstname'] . ' ' . $mail_data['sender_lastname'];
     }
     $body = sprintf(Strings::get('body_template', 'feedback'), $sender_name, $mail_data['sender_email'], $mail_data['body']);
     $body = str_replace('<br>', "\n", $body);
     $subject = $this->_getMailSubject();
     $recipient_email = $this->_getEmail();
     $mailer = $this->_getMailer();
     $headers['From'] = $mail_data['sender_email'];
     $headers['To'] = $recipient_email;
     $headers['Subject'] = $subject;
     if (!$recipient_email || !$mailer->send($recipient_email, $headers, $body)) {
         MessageBox::writeNotice(Strings::get('mail_not_sent', 'feedback'));
         $request->setStatus(Request::STATUS_FAILUER);
         return;
     }
     MessageBox::writeNotice(Strings::get('message_was_sent', 'feedback'));
     $request->setStatus(Request::STATUS_FORM_SUBMITTED);
     $response->redirect($_SERVER['PHP_SELF']);
 }
 public function process(array $documents, &$context)
 {
     $document = $documents[self::URL_MEDIA];
     $dom = self::getDOM($document);
     $xpath = new DOMXPath($dom);
     Database::delete('mediarelation', ['media_id' => $context->media->id]);
     $data = [];
     foreach ($xpath->query('//table[@class=\'anime_detail_related_anime\']/tr') as $node) {
         $typeMal = strtolower(Strings::removeSpaces($node->childNodes[0]->textContent));
         $type = Strings::makeEnum($typeMal, ['adaptation' => MediaRelation::Adaptation, 'alternative setting' => MediaRelation::AlternativeSetting, 'alternative version' => MediaRelation::AlternativeVersion, 'character' => MediaRelation::Character, 'full story' => MediaRelation::FullStory, 'other' => MediaRelation::Other, 'parent story' => MediaRelation::ParentStory, 'prequel' => MediaRelation::Prequel, 'sequel' => MediaRelation::Sequel, 'side story' => MediaRelation::SideStory, 'spin-off' => MediaRelation::SpinOff, 'summary' => MediaRelation::Summary], null);
         if ($type === null) {
             throw new BadProcessorDocumentException($document, 'unknown relation type: ' . $typeMal);
         }
         $links = $node->childNodes[1]->getElementsByTagName('a');
         foreach ($links as $link) {
             $link = $link->getAttribute('href');
             if (preg_match('#^/(anime|manga)/([0-9]+)/#', $link, $matches)) {
                 $idMal = Strings::makeInteger($matches[2]);
                 if ($matches[1] === 'anime') {
                     $media = Media::Anime;
                 } elseif ($matches[1] === 'manga') {
                     $media = Media::Manga;
                 }
                 $data[] = ['media_id' => $context->media->id, 'mal_id' => $idMal, 'media' => $media, 'type' => $type];
             }
         }
     }
     Database::insert('mediarelation', $data);
     $context->relationData = $data;
 }
  protected function check($value)
  {
    $value = "$value";

    if(!preg_match("~^[a-zA-Z]\d[a-zA-Z]\s\d[a-zA-Z]\d$~", $value))
      $this->error(Strings :: get('error_invalid_zip_format', 'error'));
  }
Esempio n. 20
0
 public static function formatForTitle($string)
 {
     if (!is_string($string) || strlen($string) === 0) {
         return false;
     }
     $string = str_replace('_', ' ', $string);
     return Strings::titleCase($string);
 }
	/**
	 * Returns a detailed error message.
	 *
	 * The error message contains:
	 * 1. Error Number (only if greater than zero)
	 * 2. Error Message
	 * 3. File Name
	 * 4. Line Number of the file
	 * 5. Executed SQL Query (optional)
	 *
	 * @return string All error details as string
	 */
	public function __toString() {
		$error = parent::__toString();
		if (empty($this->query) == false) {
			$query = Strings::replaceLineBreaks($this->query, "\t");
			$error .= "\r\nQuery: {$query}";
		}
		return $error;
	}
  public function redirect($path)
  {
    include_once(LIMB_DIR . '/class/i18n/Strings.class.php');

    $message = Strings :: get('redirect_message');//???
    $message = str_replace('%path%', $path, $message);
    $this->response_string = "<html><head><meta http-equiv=refresh content='0;url={$path}'></head><body bgcolor=white><font color=707070><small>{$message}</small></font></body></html>";
  }
Esempio n. 23
0
 /**
  * Método que define a tabela
  * @param string $tabelas Define como a tabela ou tabelas.
  */
 public function into($tabelas)
 {
     if (!\Strings::validar($tabelas)) {
         throw new SqlException("Query mal formada. A tabela é inválida");
     }
     $this->tabela = $tabelas;
     return $this;
 }
Esempio n. 24
0
 public function filter($var)
 {
     $var = parent::filter($var);
     if (!preg_match($this->options['regex'], $var)) {
         return null;
     }
     return $var;
 }
Esempio n. 25
0
 public function testCamel()
 {
     $this->assertEquals('hereIAm', Strings::camel('Here I am'));
     $this->assertEquals('hereIAm', Strings::camel('Here-I am'));
     $this->assertEquals('hereIAm', Strings::camel('Here I am!'));
     $this->assertEquals('hereIAm', Strings::camel(',Here I am'));
     $this->assertEquals('meVoila', Strings::camel('Me voilà'));
 }
Esempio n. 26
0
 /**
  * Método que defien a tabela alvo da interação
  * @param string $tabela A tabela alvo
  */
 public function setTabela($tabela)
 {
     if (!\Strings::validar($tabela)) {
         throw new SqlException("A tabela definida é inválida");
     }
     $this->tabela = $tabela;
     return $this;
 }
Esempio n. 27
0
 /**
  * @func   void
  * @return void
  */
 public function __construct()
 {
     echo 'tss1 controller works<br/>';
     /*
     load::service('validator');
     
     $rules = array
     (
         'name' => 'alpha|required',
         'year' => 'num|required',
     );
     
     $Validation = new Validator();
     $Validation->validate($_POST, $rules);
     
     if (!$Validation->passed())
     {
         $Validation->goBackWithErrors();
     }
     
     if (!empty($Validation->getErrors()))
     {
         print_r($Validation->getErrors());
     }
     */
     load::library(SF::STRINGS);
     load::library(SF::NETWORK);
     #$test_string = Strings::generate_password(4);
     $test_string = Strings::generatePassword(4);
     var_dump($test_string);
     $numeric_test = (int) '-abc12.3edf';
     // this SHOULD FALL AND THROW AN ERROR
     #var_dump(Strings::strip_to_numeric($numeric_test));
     var_dump(Strings::StripToNumeric($numeric_test));
     #var_dump(Network::get_client_lang());
     var_dump(Network::getClientLang());
     exit;
     // database testing
     $data = Entries::getData();
     var_dump($data);
     /*
     load::library(SF::DEBUG);
     //load::library(SF::DEBUG)->func('pr'); // will only load clean_str()
     
     ExecuteTime::start();
     
     $parameters = array
     (
         'key'      => '1e46165dsa5ds4a',
         'action'   => 'push',
         'userid'   => 1234998,
         'keywords' => 'test'
     );
     
     ExecuteTime::end();
     echo ExecuteTime::display();
     */
 }
  public function validate($dataspace)
  {
    $value = $dataspace->get($this->field_name);

    if (!isset($value) ||  $value === '')
    {
      $this->error(Strings :: get('error_required', 'error'));
    }
  }
Esempio n. 29
0
 /**
  * Transforms path to class name with namespaces.
  *
  * Example:
  * <code>
  * $string = 'api/multiple_ns';
  * $namespace = ClassName::pathToFullyQualifiedName($string);
  * </code>
  * Result:
  * <code>
  * Api\\MultipleNs
  * </code>
  *
  * @param $string
  * @return string
  */
 public static function pathToFullyQualifiedName($string)
 {
     $parts = explode('/', $string);
     $namespace = '';
     foreach ($parts as $part) {
         $namespace .= Strings::underscoreToCamelCase($part) . '\\';
     }
     return rtrim($namespace, '\\');
 }
	/**
	 * @dataProvider providerReplaceLineBreaks
	 */
	public function testReplaceLineBreaks($param_string, $param_replace, $expected) {
		$result = Strings::replaceLineBreaks($param_string, $param_replace);
		$this->assertEquals(
			$expected,
			$result,
			"Could not properly replace line breaks with ".var_export($param_replace, true).
				" in string ".var_export($param_string, true)
		);
	}