Example #1
0
 /**
  * MagicDb::read should properly read MagicDb databases from .php-/.db-files and plain data arguments passed in and return false if the file wasn't found or
  * if the readed data did not validate.
  *
  * @access public
  */
 function testRead()
 {
     $this->Db->db = array();
     $r = $this->Db->read(true);
     $this->assertTrue($r === false);
     $r = $this->Db->read(5);
     $this->assertTrue($r === false);
     $this->Db->db = array('a');
     $r = $this->Db->read(array('foo' => 'bar'));
     $this->assertTrue($r === false);
     $this->assertTrue($this->Db->db === array('a'));
     $magicDb = array('header' => array(), 'database' => array());
     $r = $this->Db->read($magicDb);
     $this->assertTrue($r === true);
     $this->assertTrue($this->Db->db === $magicDb);
     // @TODO: Test parsing an actual magic.db file
     $r = $this->Db->read('does-not-exist.db');
     $this->assertTrue($r === false);
     $this->assertTrue($this->Db->db === $magicDb);
     if (file_exists(VENDORS . 'magic.php')) {
         $r = $this->Db->read(VENDORS . 'magic.php');
         $this->assertTrue($r === true);
         $this->assertTrue($this->Db->db === array('header' => array(), 'database' => array()));
     }
     $r = $this->Db->read(MagicDbTestData::get('magic.snippet.db'));
     $this->assertTrue($r === true);
 }
Example #2
0
 /**
  * Gets data
  * @return array
  * @uses $file
  */
 public function get()
 {
     $data = $this->file->read();
     if (empty($data)) {
         return [];
     }
     //Unserializes
     return unserialize($data);
 }
 /**
  * Get data from the application in a certain mime type format.
  * @param integer $id id of data to get from the application
  * @param string $type specifies the mime type of the returned data
  * @param string $version specifies the mime type version of the returned data
  * @return mixed data from application, the datatype depends on the passed mime type, false if no data exists for the passed id
  */
 function getData($id, $type, $version = '')
 {
     // 1: get data
     $dataIntern = $this->bo->read($id);
     if ($dataIntern == false) {
         return false;
     }
     // 2: mapping internal data to the output mime type
     return $this->_exportData($dataIntern, $type, $version);
 }
Example #4
0
 /**
  * Read queue messages
  *
  * @return bool
  */
 public function read()
 {
     $ret = $this->implement->read(MAX_QUEUE_FILE_LOAD);
     if (!$ret || $this->implement->error()) {
         $this->error = $this->implement->error();
         return false;
     }
     $this->messages = $this->implement->elements();
     return true;
 }
 /**
  * @param $char
  * @param $prevChar
  * @return array|null
  * @throws Exception
  */
 public function read($char, $prevChar)
 {
     $this->_result = !is_null($this->_result) ? $this->_result : array();
     if (is_null($this->_status) && $prevChar == Unserialize_Parser::SYMBOL_COLON) {
         $this->_length .= $char;
         $this->_status = self::READING_LENGTH;
         return null;
     }
     if ($this->_status == self::READING_LENGTH) {
         if ($char == Unserialize_Parser::SYMBOL_COLON) {
             $this->_length = (int) $this->_length;
             if ($this->_length == 0) {
                 $this->_status = self::FINISHED_ARR;
                 return null;
             }
             $this->_status = self::FINISHED_LENGTH;
         } else {
             $this->_length .= $char;
         }
     }
     if ($this->_status == self::FINISHED_LENGTH && $prevChar == '{') {
         $this->_reader = new Unserialize_Reader_ArrKey();
         $this->_status = self::READING_KEY;
     }
     if ($this->_status == self::READING_KEY) {
         $key = $this->_reader->read($char, $prevChar);
         if (!is_null($key)) {
             $this->_status = self::READING_VALUE;
             $this->_reader = new Unserialize_Reader_ArrValue($key);
             return null;
         }
     }
     if ($this->_status == self::READING_VALUE) {
         $value = $this->_reader->read($char, $prevChar);
         if (!is_null($value)) {
             $this->_result[$this->_reader->key] = $value;
             if (count($this->_result) < $this->_length) {
                 $this->_reader = new Unserialize_Reader_ArrKey();
                 $this->_status = self::READING_KEY;
                 return null;
             } else {
                 $this->_status = self::FINISHED_ARR;
                 return null;
             }
         }
     }
     if ($this->_status == self::FINISHED_ARR) {
         if ($char == '}') {
             return $this->_result;
         }
     }
 }
Example #6
0
 /**
  * Find records
  *
  * @access public
  * @return array
  */
 public function find()
 {
     $output = array();
     $lines = $this->File->read();
     $lines = explode("\n", $lines);
     if (count($lines) > 0) {
         foreach ($lines as $line) {
             $line = trim($line);
             if (strpos($line, ':') !== false) {
                 $output[] = array($this->alias => array('username' => substr($line, 0, strpos($line, ':')), 'password' => substr($line, strpos($line, ':') + 1)));
             }
         }
     }
     return $output;
 }
Example #7
0
 /**
  * Delete all values from the cache
  *
  * @param boolean $check Optional - only delete expired cache items
  * @return boolean True if the cache was succesfully cleared, false otherwise
  * @access public
  */
 function clear($check)
 {
     if (!$this->__init) {
         return false;
     }
     $dir = dir($this->settings['path']);
     if ($check) {
         $now = time();
         $threshold = $now - $this->settings['duration'];
     }
     while (($entry = $dir->read()) !== false) {
         if ($this->__setKey($entry) === false) {
             continue;
         }
         if ($check) {
             $mtime = $this->__File->lastChange();
             if ($mtime === false || $mtime > $threshold) {
                 continue;
             }
             $expires = $this->__File->read(11);
             $this->__File->close();
             if ($expires > $now) {
                 continue;
             }
         }
         $this->__File->delete();
     }
     $dir->close();
     return true;
 }
 /**
  * Fetches cached data.
  *
  * @since 6.2.0
  * @param int|string $key
  *            Unique key of the cache file.
  * @param string $namespace
  *            Optional. Where the cache contents are namespaced.
  */
 public function read($key, $namespace = 'default')
 {
     if (empty($namespace)) {
         $namespace = 'default';
     }
     return $this->_cache->read($key, $namespace);
 }
Example #9
0
 /**
  * Session constructor.
  *
  * @param ISessionAdapter $adapter      Current adapter.
  * @param array $settings               Session and GC settigs.
  */
 public function __construct(ISessionAdapter $adapter, array $settings)
 {
     // check session settings
     if (!isset($settings['cookieName'], $settings['sessLogName'], $settings['repository'], $settings['runRate'], $settings['short'], $settings['long'])) {
         throw new RuntimeException('Some settings are not found, please, refer to documentation.');
     }
     // store given settings
     $this->settings = $settings;
     // set session repository
     $this->repository = $this->settings['repository'];
     // set session cookie name
     $this->cookieName = $this->settings['cookieName'];
     // store and configure given session adapter
     $this->adapter = $adapter->configureAdapter($this->repository);
     // check whether we can read/write from/to given session repository
     if (!$this->adapter->checkAccess($this->repository)) {
         throw new RuntimeException(sprintf("Can't work with given session repository, specified as: %s.\n                    Сheck connection or read/write permissions.", $this->repository));
     }
     /**
      * Сheck the availability information about the session ID
      * in cookies and exists of specific session.
      */
     if (isset($_COOKIE[$this->cookieName]) && $this->adapter->isExist($this->repository, $_COOKIE[$this->cookieName])) {
         // On success, split cookie value
         // on session ID and session type
         $sessCookieParts = $this->splitSessCookie($_COOKIE[$this->cookieName], $this->sessTypes);
         // session ID without type
         $this->sessID = $sessCookieParts['id'];
         // session type without ID
         $this->currentSessType = $sessCookieParts['type'];
         // read and unserialize session data from session repository
         $this->sessStorage = $this->adapter->read($this->repository, $_COOKIE[$this->cookieName]);
     }
 }
Example #10
0
 /**
  * Admin edit
  *
  * @param integer $id
  * @return void
  * @access public
  */
 public function admin_edit($id = null)
 {
     // Protect against administrator edit
     if ($id == null || $id < 4) {
         $this->Session->setFlash(__('Invalid request.'), 'flash_message_error');
         $this->redirect(array('action' => 'index'));
     }
     $errors = null;
     if (!empty($this->request->data)) {
         $this->request->data['Aro']['model'] = '';
         // update alias with user data
         if ($this->request->data['Aro']['foreign_key'] != '') {
             $this->request->data['Aro']['model'] = 'User';
             $this->request->data['Aro']['alias'] = $this->User->field('Name', array('id' => $this->request->data['Aro']['foreign_key']));
         }
         $this->Node->recursive = -1;
         $this->request->data = array_merge($this->Node->read(null, $id), $this->request->data);
         // alias must be unique
         $this->Node->validate = array('alias' => array('rule' => 'isUnique', 'message' => __('Group / User name must be unique!!')));
         if ($this->Node->save($this->request->data)) {
             $this->Session->setFlash(__('Saved with success.'), 'flash_message_info');
             $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('Could not be saved. Please, try again.'), 'flash_message_error');
         }
     }
     if (empty($this->request->data)) {
         $this->request->data = $this->Node->read(null, $id);
     }
     $parents[0] = "[ " . __('Root') . " ]";
     $nodelist = $this->Node->generateTreeList(null, '{n}.Aro.id', '{n}.Aro.alias', ' - ', '-1');
     $acolist = $this->Acl->Aco->generateTreeList(null, '{n}.Aco.id', '{n}.Aco.alias', ' - ', '-1');
     $acoAccessList = $this->Acl->Aco->generateTreeList(null, '{n}.Aco.id', '{n}.Aco.alias', '', '-1');
     $acoAliasList = $acoAccessList;
     foreach ($acoAccessList as $key => $value) {
         $alias = "";
         $path = $this->Acl->Aco->getPath($key);
         foreach ($path as $pathAlias) {
             if ($alias != '') {
                 $alias = $alias . '/';
             }
             $alias = $alias . $pathAlias['Aco']['alias'];
         }
         $acoAliasList[$key] = $alias;
         $acoAccessList[$key] = $this->Acl->check($this->request->data['Aro']['alias'], $alias);
         #value
     }
     if ($nodelist) {
         foreach ($nodelist as $key => $value) {
             $parents[$key] = $value;
         }
     }
     $foreignKeys = array();
     // if node is group type ( without foreignKey ) do no show available users
     if ($this->Node->field('foreign_key')) {
         $usersOnAro = $this->Node->find('list', array('fields' => array('Aro.foreign_key'), 'conditions' => array('Aro.foreign_key <>' => null, 'Aro.id <>' => $id)));
         $foreignKeys = $this->User->find('list', array('conditions' => array('User.active' => '1', 'NOT' => array('User.id' => $usersOnAro))));
     }
     $this->set(compact('parents', 'acolist', 'foreignKeys', 'acoAccessList', 'acoAliasList'));
 }
Example #11
0
 /**
  * Admin edit
  *
  * @param integer $id
  * @return void
  * @access public
  */
 public function admin_edit($id = null)
 {
     if ($id == null || $id < 3) {
         $this->Session->setFlash(__('Invalid request.'), 'flash_message_error');
         $this->redirect(array('action' => 'index'));
     }
     if (!empty($this->request->data)) {
         if ($this->Node->save($this->request->data)) {
             $this->Session->setFlash(__('Saved with success.'), 'flash_message_info');
             $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('Could not be saved. Please, try again.'), 'flash_message_error');
         }
     } else {
         $this->request->data = $this->Node->read(null, $id);
     }
     $parents[0] = "[ No Parent ]";
     $nodelist = $this->Node->generateTreeList(null, '{n}.Aco.id', '{n}.Aco.alias', ' - ', '-1');
     if ($nodelist) {
         foreach ($nodelist as $key => $value) {
             $parents[$key] = $value;
         }
     }
     $this->set(compact('parents'));
 }
 /**
  * @param      $pageId
  * @param null $params
  *
  * @return mixed
  */
 public function getEmailAlertCollection($pageId, $params = null)
 {
     $base_url = $this->url_components['server'] . $this->url_components['6.0'] . "profiles/%d/pages/%d/email_alerts";
     $url = sprintf($base_url, $this->url_components['profiles'], $pageId);
     $call_params = is_null($params) ? array('limit' => '100', 'offset' => '0') : $params;
     $this->api->setupRequest($this->base_params['ACCESS_TOKEN'], $call_params);
     return $this->api->read($url, true);
 }
 /**
  * Checks if data for the passed id exists.
  * @param integer $id id to check
  * @return boolean true if the data with id exist, otherwise false
  */
 function existData($id)
 {
     if ($this->bo->read($id)) {
         return true;
     } else {
         return false;
     }
 }
Example #14
0
 /**
  * Read session data and refresh session expiration
  *
  * @return array
  */
 protected static function readSession()
 {
     $data = static::$repository->read(static::$tokenId);
     if (!empty($data)) {
         static::$repository->write(static::$tokenId, $data, $refresh = true);
     }
     return $data;
 }
Example #15
0
 /**
  * 读文件
  *
  * @access  public
  * @param   string
  * @return  string/bytes
  */
 public function file_read($path = '')
 {
     $content = $this->_storage->read($this->_config['storage'], $this->_translate_path($path));
     if ($content == FALSE) {
         show_error(SaeStorage::errmsg());
     }
     return $content;
 }
Example #16
0
 /**
  * Returns the contents of the file identified in path
  *
  * @param   string $path
  *
  * @return  null|string
  * @since   1.0
  * @throws  RuntimeException
  */
 public function read($path)
 {
     try {
         return $this->adapter->read($path);
     } catch (Exception $e) {
         throw new RuntimeException('Filesystem: Read Exception ' . $e->getMessage());
     }
 }
Example #17
0
 /**
  * Move to the first node that matches our key
  *
  * @return  void
  */
 public function rewind()
 {
     // open file with reader
     // force UTF-8, validate XML, & substitute entities while reading
     $this->reader->open($this->file, 'UTF-8', XMLReader::VALIDATE | XMLReader::SUBST_ENTITIES);
     // fast forward to first record
     while ($this->reader->read() && $this->reader->name !== $this->key) {
     }
 }
Example #18
0
 /**
  * Get a list of citations requiring attention
  *
  * @return  array
  */
 public function readRequiresNoAttention()
 {
     $p = $this->getRequiresNoAttentionPath();
     $citations = null;
     if (file_exists($p)) {
         $citations = unserialize($this->filesystem->read($p));
     }
     return $citations;
 }
Example #19
0
	/**
	 * Assembles and writes a Fixture file
	 *
	 * @param string $model Name of model to bake.
	 * @param string $useTable Name of table to use.
	 * @param array $importOptions Options for var $import
	 * @return string Baked fixture content
	 * @access public
	 */
	function bake($model, $useTable = false, $importOptions = array()) {
		if (!class_exists('CakeSchema')) {
			App::import('Model', 'CakeSchema', false);
		}
		$table = $schema = $records = $import = $modelImport = null;
		$importBits = array();

		if (!$useTable) {
			$useTable = Inflector::tableize($model);
		} elseif ($useTable != Inflector::tableize($model)) {
			$table = $useTable;
		}

		if (!empty($importOptions)) {
			if (isset($importOptions['schema'])) {
				$modelImport = true;
				$importBits[] = "'model' => '{$importOptions['schema']}'";
			}
			if (isset($importOptions['records'])) {
				$importBits[] = "'records' => true";
			}
			if ($this->connection != 'default') {
				$importBits[] .= "'connection' => '{$this->connection}'";
			}
			if (!empty($importBits)) {
				$import = sprintf("array(%s)", implode(', ', $importBits));
			}
		}

		$this->_Schema = new CakeSchema();
		$data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));

		if (!isset($data['tables'][$useTable])) {
			$this->err('Could not find your selected table ' . $useTable);
			return false;
		}

		$tableInfo = $data['tables'][$useTable];
		if (is_null($modelImport)) {
			$schema = $this->_generateSchema($tableInfo);
		}

		if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
			$recordCount = 1;
			if (isset($this->params['count'])) {
				$recordCount = $this->params['count'];
			}
			$records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
		}
		if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
			$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
		}
		$out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
		return $out;
	}
 public function index()
 {
     $output = self::get_output();
     $GLOBALS['phpgw_info']['flags']['menu_selection'] .= "::{$output}";
     if (!$this->acl_read) {
         $this->no_access();
         return;
     }
     $GLOBALS['phpgw']->xslttpl->add_file(array('demo', 'nextmatchs', 'search_field'));
     $demo_info = $this->bo->read();
     foreach ($demo_info as $entry) {
         $link_view = '';
         $lang_view_demo_text = '';
         $text_view = '';
         if (demo_bodemo::check_perms($entry['grants'], PHPGW_ACL_READ)) {
             $link_view = $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'demo.uidemo.view', 'demo_id' => $entry['id'], 'output' => $output));
             $lang_view_demo_text = lang('view the demo');
             $text_view = lang('view');
         }
         $link_edit = '';
         $lang_edit_demo_text = '';
         $text_edit = '';
         if (demo_bodemo::check_perms($entry['grants'], PHPGW_ACL_EDIT)) {
             $link_edit = $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'demo.uidemo.edit', 'demo_id' => $entry['id'], 'output' => $output));
             $lang_edit_demo_text = lang('edit the demo');
             $text_edit = lang('edit');
         }
         $link_delete = '';
         $text_delete = '';
         $lang_delete_demo_text = '';
         if (demo_bodemo::check_perms($entry['grants'], PHPGW_ACL_DELETE)) {
             $link_delete = $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'demo.uidemo.delete', 'demo_id' => $entry['id'], 'output' => $output));
             $text_delete = lang('delete');
             $lang_delete_demo_text = lang('delete the demo');
         }
         $content[] = array('name' => $entry['name'], 'link_edit' => $link_edit, 'link_delete' => $link_delete, 'link_view' => $link_view, 'lang_view_demo_text' => $lang_view_demo_text, 'lang_edit_demo_text' => $lang_edit_demo_text, 'text_view' => $text_view, 'text_edit' => $text_edit, 'text_delete' => $text_delete, 'lang_delete_demo_text' => $lang_delete_demo_text);
     }
     //_debug_array($content);
     $table_header[] = array('sort_name' => $this->nextmatches->show_sort_order(array('sort' => $this->sort, 'var' => 'name', 'order' => $this->order, 'extra' => array('menuaction' => 'demo.uidemo.index', 'query' => $this->query, 'cat_id' => $this->cat_id, 'filter' => $this->filter, 'output' => $output, 'allrows' => $this->allrows))), 'lang_name' => lang('name'), 'lang_view' => lang('view'), 'lang_edit' => isset($this->acl_edit) ? lang('edit') : '', 'lang_delete' => isset($this->acl_delete) ? lang('view') : '');
     if (!$this->allrows) {
         $record_limit = $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs'];
     } else {
         $record_limit = $this->bo->total_records;
     }
     $link_data = array('menuaction' => 'demo.uidemo.index', 'sort' => $this->sort, 'order' => $this->order, 'cat_id' => $this->cat_id, 'filter' => $this->filter, 'query' => $this->query, 'output' => $output);
     $table_add[] = array('lang_add' => lang('add'), 'lang_add_statustext' => lang('add a demo'), 'add_action' => $GLOBALS['phpgw']->link('/index.php', array('menuaction' => 'demo.uidemo.edit', 'output' => $output)));
     $msgbox_data = isset($receipt) ? $GLOBALS['phpgw']->common->msgbox_data($receipt) : '';
     $data = array('msgbox_data' => $GLOBALS['phpgw']->common->msgbox($msgbox_data), 'cat_filter' => $this->cats->formatted_xslt_list(array('select_name' => 'cat_id', 'selected' => $this->cat_id, 'globals' => true, 'link_data' => $link_data)), 'filter_data' => $this->nextmatches->xslt_filter(array('filter' => $this->filter, 'link_data' => $link_data)), 'allow_allrows' => true, 'allrows' => $this->allrows, 'start_record' => $this->start, 'record_limit' => $record_limit, 'num_records' => $demo_info ? count($demo_info) : 0, 'all_records' => $this->bo->total_records, 'link_url' => $GLOBALS['phpgw']->link('/index.php', $link_data), 'img_path' => $GLOBALS['phpgw']->common->get_image_path('phpgwapi', 'default'), 'lang_searchfield_statustext' => lang('Enter the search string. To show all entries, empty this field and press the SUBMIT button again'), 'lang_searchbutton_statustext' => lang('Submit the search string'), 'query' => $this->query, 'lang_search' => lang('search'), 'table_header' => $table_header, 'table_add' => $table_add, 'values' => isset($content) ? $content : '');
     $function_msg = lang('list demo values');
     $GLOBALS['phpgw_info']['flags']['app_header'] = lang('demo') . ": {$function_msg}";
     $GLOBALS['phpgw']->xslttpl->set_var('phpgw', array("list_{$output}" => $data));
     $this->save_sessiondata();
 }
Example #21
0
 /**
  * Deletes any files that have been attached to this model
  * @access public
  * @param object $Model
  * @return boolean
  */
 public function beforeDelete(&$Model)
 {
     $data = $Model->read(null, $Model->id);
     if (!empty($data[$Model->alias])) {
         foreach ($data[$Model->alias] as $field => $value) {
             if (is_file(WWW_ROOT . $value)) {
                 $this->Uploader->delete($value);
             }
         }
     }
     return true;
 }
Example #22
0
 /**
  * get translated string with particular number
  * @param integer $num
  * @return string translated string
  */
 function get_translation_number($num)
 {
     // get a string with particular number
     // TODO: Add simple hashing [check array, add if not already there]
     $this->load_tables(true);
     $meta = $this->TRANSLATIONS[$num];
     $length = $meta[0];
     $offset = $meta[1];
     $this->STREAM->seekto($offset);
     $data = $this->STREAM->read($length);
     return (string) $data;
 }
Example #23
0
 /**
  * Fetch the users being online
  * Refers to: index.php
  *
  * @param boolean $colored_usernames Define if we want to return formatted usernames (color)
  * @return array
  */
 function getWhoIsOnline($colored_usernames = true)
 {
     // This is what we are going to return
     $arr = array('bots' => array(), 'count_anonymous' => 0, 'count_bots' => 0, 'count_guests' => 0, 'count_members' => 0, 'members' => array());
     // We only fetch the Who's Online list if the setting tells us that we can
     if ($this->mybb->settings['showwol'] != 0 && $this->mybb->usergroup['canviewonline'] != 0) {
         // Get the online users.
         $timesearch = TIME_NOW - $this->mybb->settings['wolcutoff'];
         $comma = '';
         $query = $this->db->query("\n\t\t\t\tSELECT s.sid, s.ip, s.uid, s.time, s.location, s.location1, u.username, u.invisible, u.usergroup, u.displaygroup\n\t\t\t\tFROM " . TABLE_PREFIX . "sessions s\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "users u ON (s.uid=u.uid)\n\t\t\t\tWHERE s.time>'{$timesearch}'\n\t\t\t\tORDER BY u.username ASC, s.time DESC\n\t\t\t");
         // Iterated users will be stored here to prevent double iterating one user
         $doneusers = array();
         // Fetch spiders
         $spiders = $this->cache->read("spiders");
         // Loop through all users.
         while ($user = $this->db->fetch_array($query)) {
             // Create a key to test if this user is a search bot.
             $botkey = my_strtolower(str_replace("bot=", '', $user['sid']));
             // Decide what type of user we are dealing with.
             if ($user['uid'] > 0) {
                 // The user is registered.
                 if ($doneusers[$user['uid']] < $user['time'] || !$doneusers[$user['uid']]) {
                     // If the user is logged in anonymously, update the count for that.
                     if ($user['invisible'] == 1) {
                         ++$arr['count_anonymous'];
                     }
                     if ($user['invisible'] != 1 || $this->mybb->usergroup['canviewwolinvis'] == 1 || $user['uid'] == $this->mybb->user['uid']) {
                         // Maybe we don't want colored usernames
                         if ($colored_usernames == true) {
                             // Properly format the username and assign the template.
                             $user['username'] = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
                         }
                         $user['profilelink'] = build_profile_link($user['username'], $user['uid']);
                     }
                     // This user has been handled.
                     $doneusers[$user['uid']] = $user['time'];
                     // Add the user to the members, since he is registered and logged in
                     $arr['members'][] = $user;
                     // Increase member counter
                     ++$arr['count_members'];
                 }
             } elseif (my_strpos($user['sid'], "bot=") !== false && $spiders[$botkey]) {
                 ++$arr['count_bots'];
                 $arr['bots'][] = $spiders[$botkey];
             } else {
                 ++$arr['count_guests'];
             }
         }
     }
     return $arr;
 }
Example #24
0
 /**
  * Detect a flooding attempt
  *
  * @access public
  * @param  array   $limits    Array of defined limits.
  * @param  string  $uniqueId  Unique identifier.
  * @return bool    False, in case of flooding attempt detected.
  * @throws HTTP_FloodControl_Exception if an error occured during checking process.
  */
 public function check($limits, $uniqueId = '')
 {
     if (is_null($this->_container)) {
         throw new HTTP_FloodControl_Exception('The container is undefined.');
     }
     if (!is_array($limits)) {
         throw new HTTP_FloodControl_Exception('Incorrect format of limits array.');
     }
     if (empty($uniqueId)) {
         $uniqueId = self::getUserIP();
     }
     list($usec, $sec) = explode(' ', microtime());
     mt_srand((double) $sec + (double) $usec * 100000);
     if (mt_rand(0, 100) < $this->_gcProbability) {
         try {
             $this->_container->gc($this->_lifetime);
         } catch (HTTP_FloodControl_Exception $e) {
             throw new HTTP_FloodControl_Exception('Unable to execute the garbage collection.', $e);
         }
     }
     $data = array();
     try {
         $data = $this->_container->read($uniqueId);
     } catch (HTTP_FloodControl_Exception $e) {
         throw new HTTP_FloodControl_Exception('Unable to read the data.', $e);
     }
     $no_flood = true;
     foreach ($limits as $interval => $limit) {
         if (!isset($data[$interval])) {
             $data[$interval]['time'] = time();
             $data[$interval]['count'] = 0;
         }
         $data[$interval]['count'] += 1;
         if (time() - $data[$interval]['time'] > $interval) {
             $data[$interval]['count'] = 1;
             $data[$interval]['time'] = time();
         }
         if ($data[$interval]['count'] > $limit) {
             if ($this->_incrementalLock) {
                 $data[$interval]['time'] = time();
             }
             $no_flood = false;
         }
     }
     try {
         $this->_container->write($uniqueId, $data);
     } catch (HTTP_FloodControl_Exception $e) {
         throw new HTTP_FloodControl_Exception('Unable to write the data.', $e);
     }
     return $no_flood;
 }
Example #25
0
 /**
  * Process queue
  *
  * @return bool
  */
 public function process()
 {
     if ($this->error() || !$this->initialize()) {
         return false;
     }
     while (!$this->queue->isEmpty()) {
         $this->queue->read();
         if ($this->queue->error()) {
             $this->error('Read queue messages failure,error:' . $this->queue->error());
             Logger::error($this->error());
             return false;
         }
         while (($message = $this->queue->pop()) !== null) {
             $error = false;
             $mid = key($message);
             $content = trim($message[$mid]);
             $lines = explode("\n", $content);
             foreach ($lines as $line) {
                 if (DEBUG) {
                     $timestart = microtime(true);
                 }
                 if (!$this->doProcess($line)) {
                     $error = true;
                     continue;
                 }
                 if (DEBUG) {
                     $timeend = microtime(true);
                     Logger::trace('Process successful,time uered: ' . round($timeend - $timestart, 3));
                 }
             }
             if (!$error) {
                 $this->queue->remove($mid);
             }
         }
     }
     return $this->finalize();
 }
Example #26
0
 /**
  * testSave
  *
  * @retun void
  * @access public
  */
 function testSave()
 {
     $data = array('Produto' => array('nome' => 'Produto 4', 'valor' => '5.000,00'));
     $this->Produto->create();
     $this->assertTrue($this->Produto->save($data));
     $id = $this->Produto->getInsertId();
     $data['Produto']['id'] = $id;
     $result = $this->Produto->read(null, $id);
     $this->assertEqual($data, $result);
     $result = $this->Produto->read(array('valor'), $id);
     $this->assertEqual(array('Produto' => array('valor' => '5.000,00')), $result);
     $result = $this->Produto->read(array('nome'), $id);
     // Verificar se dá erro quando não vem o campo
     $this->assertEqual(array('Produto' => array('nome' => 'Produto 4')), $result);
 }
Example #27
0
 /**
  * Deletes any files that have been attached to this model.
  *
  * @access public
  * @param object $Model
  * @return boolean
  */
 public function beforeDelete(&$Model)
 {
     $data = $Model->read(null, $Model->id);
     if (!empty($data[$Model->alias])) {
         foreach ($data[$Model->alias] as $field => $value) {
             if (strpos($value, 's3.amazonaws.com') !== false) {
                 $this->S3Transfer->delete($value);
             } else {
                 if (is_file(WWW_ROOT . $value)) {
                     $this->Uploader->delete($value);
                 }
             }
         }
     }
     return true;
 }
Example #28
0
 /**
  * Disable
  *
  * @access public
  * @return boolean
  */
 public function disable()
 {
     $contents = $this->File->read();
     //Lines to remove
     $remove = array();
     $protection = explode("\n", $this->protection);
     foreach ($protection as $line) {
         $remove[] = '/' . substr($line, 0, strpos($line, ' ')) . '.*$/s';
     }
     $newContents = preg_replace($remove, '', $contents);
     if ($contents != $newContents) {
         return $this->File->write($newContents);
     } else {
         return false;
     }
 }
Example #29
0
 public function beforeDelete(Model $model, $cascade = true)
 {
     //public function beforeDelete(){
     foreach ($this->__files as $field => $options) {
         $arquivo = $this->__model->read($field);
         $arquivo = $arquivo[$this->__model->alias][$field];
         if (!empty($options['sizes']) && count($options['sizes']) > 0) {
             foreach ($options['sizes'] as $tamanho => $setting) {
                 if ($tamanho == 'normal') {
                     continue;
                 }
                 @unlink($this->__fullPathDir($options['dir']) . DS . $tamanho . '_' . $arquivo);
             }
         }
         @unlink($this->__fullPathDir($options['dir']) . DS . $arquivo);
     }
     return true;
 }
Example #30
0
 /**
  * Constructor
  *
  * @param   string  $store    The type of storage for the session.
  * @param   array   $options  Optional parameters
  */
 public function __construct($store = 'none', $options = array())
 {
     // Need to destroy any existing sessions started with session.auto_start
     if (session_id()) {
         session_unset();
         session_destroy();
     }
     // Set default sessios save handler
     ini_set('session.save_handler', 'files');
     // Disable transparent sid support
     ini_set('session.use_trans_sid', '0');
     if ($store == 'database') {
         if (ini_get('session.gc_probability') < 1) {
             ini_set('session.gc_probability', 1);
         }
         if (ini_get('session.gc_divisor') < 1) {
             ini_set('session.gc_divisor', 100);
         }
     }
     // Create handler
     $this->store = Store::getInstance($store, $options);
     // Set options
     $this->setOptions($options);
     // Pass session id in query string when cookie not available.
     // This is used, in particular, to allow QuickTime plugin in Safari on the Mac
     // to view private mp4. QuickTime does not pass the browser's cookies to the site
     if (!isset($_COOKIE[session_name()]) && isset($_GET['PHPSESSID'])) {
         if (strlen($_GET['PHPSESSID']) == 32 && ctype_alnum($_GET['PHPSESSID'])) {
             if ($this->store->read($_GET['PHPSESSID']) != '') {
                 session_id($_GET['PHPSESSID']);
             }
         }
     }
     $this->setCookieParams();
     // Load the session
     $this->start();
     // Initialise the session
     $this->setCounter();
     $this->setTimers();
     $this->state = 'active';
     // Perform security checks
     $this->validate();
 }