_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q259700 | gapi.accountObjectMapper | test | protected function accountObjectMapper($json_string) {
$json = json_decode($json_string, true);
$results = array();
foreach ($json['items'] as $item) {
foreach ($item['webProperties'] as $property) {
if (isset($property['profiles'][0]['id'])) {
$property['ProfileId'] = $property['profiles'][0]['id'];
}
$results[] = new gapiAccountEntry($property);
}
}
$this->account_entries = $results;
return $results;
} | php | {
"resource": ""
} |
q259701 | gapi.reportObjectMapper | test | protected function reportObjectMapper($json_string) {
$json = json_decode($json_string, true);
$this->results = null;
$results = array();
$report_aggregate_metrics = array();
//Load root parameters
// Start with elements from the root level of the JSON that aren't themselves arrays.
$report_root_parameters = array_filter($json, function($var){
return !is_array($var);
});
// Get the items from the 'query' object, and rename them slightly.
foreach($json['query'] as $index => $value) {
$new_index = lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $index))));
$report_root_parameters[$new_index] = $value;
}
// Now merge in the profileInfo, as this is also mostly useful.
array_merge($report_root_parameters, $json['profileInfo']);
//Load result aggregate metrics
foreach($json['totalsForAllResults'] as $index => $metric_value) {
//Check for float, or value with scientific notation
if (preg_match('/^(\d+\.\d+)|(\d+E\d+)|(\d+.\d+E\d+)$/', $metric_value)) {
$report_aggregate_metrics[str_replace('ga:', '', $index)] = floatval($metric_value);
} else {
$report_aggregate_metrics[str_replace('ga:', '', $index)] = intval($metric_value);
}
}
//Load result entries
if(isset($json['rows'])){
foreach($json['rows'] as $row) {
$metrics = array();
$dimensions = array();
foreach($json['columnHeaders'] as $index => $header) {
switch($header['columnType']) {
case 'METRIC':
$metric_value = $row[$index];
//Check for float, or value with scientific notation
if(preg_match('/^(\d+\.\d+)|(\d+E\d+)|(\d+.\d+E\d+)$/',$metric_value)) {
$metrics[str_replace('ga:', '', $header['name'])] = floatval($metric_value);
} else {
$metrics[str_replace('ga:', '', $header['name'])] = intval($metric_value);
}
break;
case 'DIMENSION':
$dimensions[str_replace('ga:', '', $header['name'])] = strval($row[$index]);
break;
default:
throw new Exception("GAPI: Unrecognized columnType '{$header['columnType']}' for columnHeader '{$header['name']}'");
}
}
$results[] = new gapiReportEntry($metrics, $dimensions);
}
}
$this->report_root_parameters = $report_root_parameters;
$this->report_aggregate_metrics = $report_aggregate_metrics;
$this->results = $results;
return $results;
} | php | {
"resource": ""
} |
q259702 | gapi.ArrayKeyExists | test | public static function ArrayKeyExists($key, $search) {
if (array_key_exists($key, $search)) {
return $key;
}
if (!(is_string($key) && is_array($search))) {
return false;
}
$key = strtolower($key);
foreach ($search as $k => $v) {
if (strtolower($k) == $key) {
return $k;
}
}
return false;
} | php | {
"resource": ""
} |
q259703 | gapiOAuth2.fetchToken | test | public function fetchToken($client_email, $key_file, $delegate_email = null) {
$header = array(
"alg" => self::header_alg,
"typ" => self::header_typ,
);
$claimset = array(
"iss" => $client_email,
"scope" => self::scope_url,
"aud" => self::request_url,
"exp" => time() + (60 * 60),
"iat" => time(),
);
if(!empty($delegate_email)) {
$claimset["sub"] = $delegate_email;
}
$data = $this->base64URLEncode(json_encode($header)) . '.' . $this->base64URLEncode(json_encode($claimset));
if (!file_exists($key_file)) {
if ( !file_exists(__DIR__ . DIRECTORY_SEPARATOR . $key_file) ) {
throw new Exception('GAPI: Failed load key file "' . $key_file . '". File could not be found.');
} else {
$key_file = __DIR__ . DIRECTORY_SEPARATOR . $key_file;
}
}
$key_data = file_get_contents($key_file);
if (empty($key_data)) {
throw new Exception('GAPI: Failed load key file "' . $key_file . '". File could not be opened or is empty.');
}
openssl_pkcs12_read($key_data, $certs, 'notasecret');
if (!isset($certs['pkey'])) {
throw new Exception('GAPI: Failed load key file "' . $key_file . '". Unable to load pkcs12 check if correct p12 format.');
}
openssl_sign($data, $signature, openssl_pkey_get_private($certs['pkey']), "sha256");
$post_variables = array(
'grant_type' => self::grant_type,
'assertion' => $data . '.' . $this->base64URLEncode($signature),
);
$url = new gapiRequest(self::request_url);
$response = $url->post(null, $post_variables);
$auth_token = json_decode($response['body'], true);
if (substr($response['code'], 0, 1) != '2' || !is_array($auth_token) || empty($auth_token['access_token'])) {
throw new Exception('GAPI: Failed to authenticate user. Error: "' . strip_tags($response['body']) . '"');
}
$this->auth_token = $auth_token['access_token'];
return $this->auth_token;
} | php | {
"resource": ""
} |
q259704 | gapiRequest.getUrl | test | public function getUrl($get_variables=null) {
if (is_array($get_variables)) {
$get_variables = '?' . str_replace('&', '&', urldecode(http_build_query($get_variables, '', '&')));
} else {
$get_variables = null;
}
return $this->url . $get_variables;
} | php | {
"resource": ""
} |
q259705 | gapiRequest.post | test | public function post($get_variables=null, $post_variables=null, $headers=null) {
return $this->request($get_variables, $post_variables, $headers);
} | php | {
"resource": ""
} |
q259706 | gapiRequest.get | test | public function get($get_variables=null, $headers=null) {
return $this->request($get_variables, null, $headers);
} | php | {
"resource": ""
} |
q259707 | gapiRequest.request | test | public function request($get_variables=null, $post_variables=null, $headers=null) {
$interface = self::http_interface;
if (self::http_interface == 'auto')
$interface = function_exists('curl_exec') ? 'curl' : 'fopen';
switch ($interface) {
case 'curl':
return $this->curlRequest($get_variables, $post_variables, $headers);
case 'fopen':
return $this->fopenRequest($get_variables, $post_variables, $headers);
default:
throw new Exception('Invalid http interface defined. No such interface "' . self::http_interface . '"');
}
} | php | {
"resource": ""
} |
q259708 | gapiRequest.curlRequest | test | private function curlRequest($get_variables=null, $post_variables=null, $headers=null) {
$ch = curl_init();
if (is_array($get_variables)) {
$get_variables = '?' . str_replace('&', '&', urldecode(http_build_query($get_variables, '', '&')));
} else {
$get_variables = null;
}
curl_setopt($ch, CURLOPT_URL, $this->url . $get_variables);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //CURL doesn't like google's cert
if (is_array($post_variables)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_variables, '', '&'));
}
if (is_array($headers)) {
$string_headers = array();
foreach ($headers as $key => $value) {
$string_headers[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $string_headers);
}
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array('body' => $response, 'code' => $code);
} | php | {
"resource": ""
} |
q259709 | gapiRequest.fopenRequest | test | private function fopenRequest($get_variables=null, $post_variables=null, $headers=null) {
$http_options = array('method'=>'GET', 'timeout'=>3);
$string_headers = '';
if (is_array($headers)) {
foreach ($headers as $key => $value) {
$string_headers .= "$key: $value\r\n";
}
}
if (is_array($get_variables)) {
$get_variables = '?' . str_replace('&', '&', urldecode(http_build_query($get_variables, '', '&')));
}
else {
$get_variables = null;
}
if (is_array($post_variables)) {
$post_variables = str_replace('&', '&', urldecode(http_build_query($post_variables, '', '&')));
$http_options['method'] = 'POST';
$string_headers = "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($post_variables) . "\r\n" . $string_headers;
$http_options['header'] = $string_headers;
$http_options['content'] = $post_variables;
}
else {
$post_variables = '';
$http_options['header'] = $string_headers;
}
$context = stream_context_create(array('http'=>$http_options));
$response = @file_get_contents($this->url . $get_variables, null, $context);
return array('body'=>$response!==false?$response:'Request failed, consider using php5-curl module for more information.', 'code'=>$response!==false?'200':'400');
} | php | {
"resource": ""
} |
q259710 | DashboardRecentFilesPanel.RecentFiles | test | public function RecentFiles() {
$records = File::get()
->filter(array(
'ClassName:not' => 'Folder'
))
->sort("LastEdited DESC")
->limit($this->Count);
$set = ArrayList::create(array());
foreach($records as $r) {
$set->push(ArrayData::create(array(
'EditLink' => Injector::inst()->get("AssetAdmin")->Link("EditForm/field/File/item/{$r->ID}/edit"),
'Title' => $r->Title
)));
}
return $set;
} | php | {
"resource": ""
} |
q259711 | DashboardPanel.duplicate | test | public function duplicate($dowrite = true) {
$clone = parent::duplicate(true);
foreach($this->has_many() as $relationName => $relationClass) {
foreach($this->$relationName() as $relObject) {
$relClone = $relObject->duplicate(false);
$relClone->DashboardPanelID = $clone->ID;
$relClone->write();
}
}
return $clone;
} | php | {
"resource": ""
} |
q259712 | DashboardModelAdminPanel.getTemplate | test | protected function getTemplate() {
$templateName = get_class($this) . '_' . $this->ModelAdminClass . '_' . $this->ModelAdminModel;
if(SS_TemplateLoader::instance()->findTemplates($templateName)) {
return $templateName;
}
return parent::getTemplate();
} | php | {
"resource": ""
} |
q259713 | DashboardModelAdminPanel.ViewAllLink | test | public function ViewAllLink() {
if($this->ModelAdminClass && $this->ModelAdminModel) {
$url_segment = Injector::inst()->get($this->ModelAdminClass)->Link();
return Controller::join_links($url_segment, $this->ModelAdminModel);
}
} | php | {
"resource": ""
} |
q259714 | DashboardModelAdminPanel.ModelAdminItems | test | public function ModelAdminItems() {
if($this->ModelAdminModel) {
$SNG= Injector::inst()->get($this->ModelAdminModel);
if($SNG->hasExtension("Versioned")) {
Versioned::reading_stage("Stage");
}
$records = DataList::create($this->ModelAdminModel)
->limit($this->Count)
->sort("LastEdited DESC");
$url_segment = Injector::inst()->get($this->ModelAdminClass)->Link();
$ret = ArrayList::create(array());
foreach($records as $rec) {
$rec->EditLink = Controller::join_links(
$url_segment,
$this->ModelAdminModel,
"EditForm",
"field",
$this->ModelAdminModel,
"item",
$rec->ID,
"edit"
);
$ret->push($rec);
}
return $ret;
}
} | php | {
"resource": ""
} |
q259715 | DashboardModelAdmin_PanelRequest.modelsforpanel | test | public function modelsforpanel(SS_HTTPRequest $r) {
$panel = $r->requestVar('modeladminpanel');
return Convert::array2json($this->panel->getManagedModelsFor($panel));
} | php | {
"resource": ""
} |
q259716 | Dashboard.providePermissions | test | public function providePermissions() {
$title = _t("Dashboard.MENUTITLE", LeftAndMain::menu_title_for_class('Dashboard'));
return array(
"CMS_ACCESS_Dashboard" => array(
'name' => _t('Dashboard.ACCESS', "Access to '{title}' section", array('title' => $title)),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t(
'Dashboard.ACCESS_HELP',
'Allow use of the CMS Dashboard'
)
),
"CMS_ACCESS_DashboardAddPanels" => array(
'name' => _t('Dashboard.ADDPANELS', "Add dashboard panels"),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t(
'Dashboard.ACCESS_HELP',
'Allow user to add panels to his/her dashboard'
)
),
"CMS_ACCESS_DashboardConfigurePanels" => array(
'name' => _t('Dashboard.CONFIGUREANELS', "Configure dashboard panels"),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t(
'Dashboard.ACCESS_HELP',
'Allow user to configure his/her dashboard panels'
),
),
"CMS_ACCESS_DashboardDeletePanels" => array(
'name' => _t('Dashboard.DELETEPANELS', "Remove dashboard panels"),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t(
'Dashboard.ACCESS_HELP',
'Allow user to remove panels from his/her dashboard'
)
)
);
} | php | {
"resource": ""
} |
q259717 | Dashboard.sort | test | public function sort(SS_HTTPRequest $r) {
if($sort = $r->requestVar('dashboard-panel')) {
foreach($sort as $index => $id) {
if($panel = DashboardPanel::get()->byID((int) $id)) {
if($panel->MemberID == Member::currentUserID()) {
$panel->SortOrder = $index;
$panel->write();
}
}
}
}
} | php | {
"resource": ""
} |
q259718 | Dashboard.setdefault | test | public function setdefault(SS_HTTPRequest $r) {
foreach(SiteConfig::current_site_config()->DashboardPanels() as $panel) {
$panel->delete();
}
foreach(Member::currentUser()->DashboardPanels() as $panel) {
$clone = $panel->duplicate();
$clone->MemberID = 0;
$clone->SiteConfigID = SiteConfig::current_site_config()->ID;
$clone->write();
}
return new SS_HTTPResponse(_t('Dashboard.SETASDEFAULTSUCCESS','Success! This dashboard configuration has been set as the default for all new members.'));
} | php | {
"resource": ""
} |
q259719 | Dashboard.applytoall | test | public function applytoall(SS_HTTPRequest $r) {
$members = Permission::get_members_by_permission(array("CMS_ACCESS_Dashboard","ADMIN"));
foreach($members as $member) {
if($member->ID == Member::currentUserID()) continue;
$member->DashboardPanels()->removeAll();
foreach(Member::currentUser()->DashboardPanels() as $panel) {
$clone = $panel->duplicate();
$clone->MemberID = $member->ID;
$clone->write();
}
}
return new SS_HTTPResponse(_t('Dashboard.APPLYTOALLSUCCESS','Success! This dashboard configuration has been applied to all members who have dashboard access.'));
} | php | {
"resource": ""
} |
q259720 | Dashboard_PanelRequest.panel | test | public function panel(SS_HTTPRequest $r) {
if($this->panel->canView()) {
return $this->panel->PanelHolder();
}
return $this->httpError(403);
} | php | {
"resource": ""
} |
q259721 | Dashboard_PanelRequest.delete | test | public function delete(SS_HTTPRequest $r) {
if($this->panel->canDelete()) {
$this->panel->delete();
return new SS_HTTPResponse("OK");
}
} | php | {
"resource": ""
} |
q259722 | Dashboard_PanelRequest.ConfigureForm | test | public function ConfigureForm() {
$form = Form::create(
$this,
"ConfigureForm",
$this->panel->getConfiguration(),
FieldList::create(
FormAction::create("saveConfiguration",_t('Dashboard.SAVE','Save'))
->setUseButtonTag(true)
->addExtraClass('ss-ui-action-constructive'),
FormAction::create("cancel",_t('Dashboard.CANCEL','Cancel'))
->setUseButtonTag(true)
)
);
$form->loadDataFrom($this->panel);
$form->setHTMLID("Form_ConfigureForm_".$this->panel->ID);
$form->addExtraClass("configure-form");
return $form;
} | php | {
"resource": ""
} |
q259723 | Dashboard_PanelRequest.saveConfiguration | test | public function saveConfiguration($data, $form) {
$panel = $this->panel;
$form->saveInto($panel);
$panel->write();
} | php | {
"resource": ""
} |
q259724 | DashboardSectionEditorPanel.Icon | test | public function Icon() {
$s = $this->Subject ? $this->Subject : "SiteTree";
$file = Config::inst()->get($s, "icon", Config::INHERITED).".png";
if(!Director::fileExists($file)) {
$file = Config::inst()->get($s, "icon", Config::INHERITED)."-file.gif";
}
if(!Director::fileExists($file)) {
$file = "dashboard/images/section-editor.png";
}
return $file;
} | php | {
"resource": ""
} |
q259725 | DashboardGoogleAnalyticsPanel.seconds_to_minutes | test | public static function seconds_to_minutes($seconds) {
$minResult = floor($seconds/60);
if($minResult < 10){$minResult = 0 . $minResult;}
$secResult = ($seconds/60 - $minResult)*60;
if($secResult < 10){$secResult = 0 . round($secResult);}
else { $secResult = round($secResult); }
return $minResult.":".$secResult;
} | php | {
"resource": ""
} |
q259726 | DashboardGoogleAnalyticsPanel.api | test | public function api() {
if(!$this->gapi) {
try {
$this->gapi = new gapi(
self::config()->email,
Director::getAbsFile(self::config()->key_file_path)
);
}
catch(Exception $e) {
$this->error = $e->getMessage();
return $this->gapi;
}
}
return $this->gapi;
} | php | {
"resource": ""
} |
q259727 | DashboardGoogleAnalyticsPanel.getConfiguration | test | public function getConfiguration() {
$fields = parent::getConfiguration();
if(!$this->isValid()) {
$fields->push(LiteralField::create("warning",_t('Dashboard.NOGOOGLEACCOUNT','<p>You have not configured a valid Google Analytics account.</p>')));
return $fields;
}
$pages = $this->getHierarchy(0);
$fields->push(OptionsetField::create("PathType",_t('Dashboard.FILTERBYPAGE','Filter'),array(
'none' => _t('Dashboard.NONESHOWALL','No filter. Show analytics for the entire site'),
'list' => _t('Dashboard.PAGEINLIST','Filter by a specific page in the tree'),
'custom' => _t('Dashboard.ACUSTOMPATH','Filter by a specific path')
)));
$fields->push(DropdownField::create("SubjectPageID",'',$pages)
->addExtraClass('no-chzn')
->setEmptyString("-- " . _t('Dashboard.PLEASESELECT','Please select')." --")
);
$fields->push(TextField::create("CustomPath", '')
->setAttribute('placeholder','e.g. /about-us/contact')
);
$fields->push(DropdownField::create("DateFormat",_t('Dashboard.DATEFORMAT','Date format'),array(
'dmy' => date('j M, Y'),
'mdy' => date('M j, Y')
))
->addExtraClass('no-chzn')
);
$fields->push(DropdownField::create("DateRange", _t('Dashboard.DATERANGE','Date range'),array(
'day' => _t('Dashboard.TODAY','Today'),
'week' => _t('Dashboard.PREVIOUSSEVENDAYS','7 days'),
'month' => _t('Dashboard.PREVIOUSTHIRTYDAYS','30 days'),
'year' => _t('Dashboard.PREVIOUSYEAR','365 days')
))
->addExtraClass('no-chzn')
);
return $fields;
} | php | {
"resource": ""
} |
q259728 | DashboardGoogleAnalyticsPanel.IsConfigured | test | public function IsConfigured() {
$c = self::config();
return (
$c->email &&
$c->key_file_path &&
$c->profile &&
Director::fileExists($c->key_file_path)
);
} | php | {
"resource": ""
} |
q259729 | DashboardGoogleAnalyticsPanel.getPath | test | public function getPath() {
if($this->PathType == "list") {
return $this->SubjectPage()->exists() ? $this->SubjectPage()->Link() : "/";
}
elseif($this->PathType == "custom") {
return $this->CustomPath;
}
} | php | {
"resource": ""
} |
q259730 | DashboardGoogleAnalyticsPanel.ChartTitle | test | public function ChartTitle() {
$stamp = $this->getStartDateStamp();
$key = $this->DateFormat == "dmy" ? "j M, Y" : "M j, Y";
$title = date($key, $stamp) . " - " . date($key);
if($this->getPath()) {
$title .= " ("._t('Dashboard.PATH','Path').": {$this->getPath()})";
}
else {
$title .= " ("._t('Dashboard.ENTIRESITE','Entire site').")";
}
return $title;
} | php | {
"resource": ""
} |
q259731 | Single.read | test | public function read(BinaryReader &$br, $length = null)
{
if (!$br->canReadBytes(4)) {
throw new \OutOfBoundsException('Cannot read 4-bytes floating-point, it exceeds the boundary of the file');
}
$segment = $br->readFromHandle(4);
if ($br->getCurrentBit() !== 0) {
$data = unpack('N', $segment)[1];
$data = $this->bitReader($br, $data);
$endian = $br->getMachineByteOrder() === $br->getEndian() ? 'N' : 'V';
$segment = pack($endian, $data);
} elseif ($br->getMachineByteOrder() !== $br->getEndian()) {
$segment = pack('N', unpack('V', $segment)[1]);
}
$value = unpack('f', $segment)[1];
return $value;
} | php | {
"resource": ""
} |
q259732 | Byte.read | test | public function read(BinaryReader &$br, $length = null)
{
if (!is_int($length)) {
throw new InvalidDataException('The length parameter must be an integer');
}
$br->align();
if (!$br->canReadBytes($length)) {
throw new \OutOfBoundsException('Cannot read bytes, it exceeds the boundary of the file');
}
$segment = $br->readFromHandle($length);
return $segment;
} | php | {
"resource": ""
} |
q259733 | Endian.convert | test | public function convert($value)
{
$data = dechex($value);
if (strlen($data) <= 2) {
return $value;
}
$unpack = unpack("H*", strrev(pack("H*", $data)));
$converted = hexdec($unpack[1]);
return $converted;
} | php | {
"resource": ""
} |
q259734 | Bit.read | test | public function read(BinaryReader &$br, $length)
{
if (!is_int($length)) {
throw new InvalidDataException('The length parameter must be an integer');
}
$bitmask = new BitMask();
$result = 0;
$bits = $length;
$shift = $br->getCurrentBit();
if ($shift != 0) {
$bitsLeft = 8 - $shift;
if ($bitsLeft < $bits) {
$bits -= $bitsLeft;
$result = ($br->getNextByte() >> $shift) << $bits;
} elseif ($bitsLeft > $bits) {
$br->setCurrentBit($br->getCurrentBit() + $bits);
return ($br->getNextByte() >> $shift) & $bitmask->getMask($bits, BitMask::MASK_LO);
} else {
$br->setCurrentBit(0);
return $br->getNextByte() >> $shift;
}
}
if (!$br->canReadBytes($length / 8)) {
throw new \OutOfBoundsException('Cannot read bits, it exceeds the boundary of the file');
}
if ($bits >= 8) {
$bytes = intval($bits / 8);
if ($bytes == 1) {
$bits -= 8;
$result |= ($this->getSigned() ? $br->readInt8() : $br->readUInt8()) << $bits;
} elseif ($bytes == 2) {
$bits -= 16;
$result |= ($this->getSigned() ? $br->readInt16() : $br->readUInt16()) << $bits;
} elseif ($bytes == 4) {
$bits -= 32;
$result |= ($this->getSigned() ? $br->readInt32() : $br->readUInt32()) << $bits;
} else {
while ($bits > 8) {
$bits -= 8;
$result |= ($this->getSigned() ? $br->readInt8() : $br->readUInt8()) << 8;
}
}
}
if ($bits != 0) {
$code = $this->getSigned() ? 'c' : 'C';
$data = unpack($code, $br->readFromHandle(1));
$br->setNextByte($data[1]);
$result |= $br->getNextByte() & $bitmask->getMask($bits, BitMask::MASK_LO);
}
$br->setCurrentBit($bits);
return $result;
} | php | {
"resource": ""
} |
q259735 | Bit.readSigned | test | public function readSigned(&$br, $length)
{
$this->setSigned(true);
$value = $this->read($br, $length);
$this->setSigned(false);
return $value;
} | php | {
"resource": ""
} |
q259736 | Int16.read | test | public function read(BinaryReader &$br, $length = null)
{
if (!$br->canReadBytes(2)) {
throw new \OutOfBoundsException('Cannot read 16-bit int, it exceeds the boundary of the file');
}
$endian = $br->getEndian() == Endian::ENDIAN_BIG ? $this->endianBig : $this->endianLittle;
$segment = $br->readFromHandle(2);
$data = unpack($endian, $segment);
$data = $data[1];
if ($br->getCurrentBit() != 0) {
$data = $this->bitReader($br, $data);
}
return $data;
} | php | {
"resource": ""
} |
q259737 | Int16.readSigned | test | public function readSigned(&$br)
{
$this->setEndianBig('s');
$this->setEndianLittle('s');
$value = $this->read($br);
$this->setEndianBig('n');
$this->setEndianLittle('v');
$endian = new Endian();
if ($br->getMachineByteOrder() != Endian::ENDIAN_LITTLE && $br->getEndian() == Endian::ENDIAN_LITTLE) {
return $endian->convert($value);
} else {
return $value;
}
} | php | {
"resource": ""
} |
q259738 | Int64.read | test | public function read(BinaryReader &$br, $length = null)
{
if (!$br->canReadBytes(8)) {
throw new \OutOfBoundsException('Cannot read 64-bit int, it exceeds the boundary of the file');
}
$endian = $br->getEndian() == Endian::ENDIAN_BIG ? $this->endianBig : $this->endianLittle;
$firstSegment = $br->readFromHandle(4);
$secondSegment = $br->readFromHandle(4);
$firstHalf = unpack($endian, $firstSegment)[1];
$secondHalf = unpack($endian, $secondSegment)[1];
if ($br->getEndian() == Endian::ENDIAN_BIG) {
$value = bcadd($secondHalf, bcmul($firstHalf, "4294967296"));
} else {
$value = bcadd($firstHalf, bcmul($secondHalf, "4294967296"));
}
if ($br->getCurrentBit() != 0) {
$value = $this->bitReader($br, $value);
}
return $value;
} | php | {
"resource": ""
} |
q259739 | Int64.readSigned | test | public function readSigned(&$br)
{
$value = $this->read($br);
if (bccomp($value, bcpow(2, 63)) >= 0) {
$value = bcsub($value, bcpow(2, 64));
}
return $value;
} | php | {
"resource": ""
} |
q259740 | StackdriverExporter.export | test | public function export(array $spans)
{
if (empty($spans)) {
return false;
}
// Pull the traceId from the first span
$spans = array_map([SpanConverter::class, 'convertSpan'], $spans);
$rootSpan = $spans[0];
$trace = self::$client->trace(
$rootSpan->traceId()
);
// build a Trace object and assign Spans
$trace->setSpans($spans);
try {
return $this->batchRunner->submitItem($this->identifier, $trace);
} catch (\Exception $e) {
error_log('Reporting the Trace data failed: ' . $e->getMessage());
return false;
}
} | php | {
"resource": ""
} |
q259741 | StackdriverExporter.getCallback | test | protected function getCallback()
{
if (!isset(self::$client)) {
self::$client = new TraceClient($this->clientConfig);
}
return [self::$client, $this->batchMethod];
} | php | {
"resource": ""
} |
q259742 | PHPCrawlerRobotsTxtParser.parseRobotsTxt | test | public function parseRobotsTxt(PHPCrawlerURLDescriptor $Url, $user_agent_string)
{
PHPCrawlerBenchmark::start("processing_robotstxt");
// URL of robots-txt
$RobotsTxtUrl = self::getRobotsTxtURL($Url);
// Get robots.txt-content related to the given URL
$robots_txt_content = $this->getRobotsTxtContent($RobotsTxtUrl);
$non_follow_reg_exps = array();
// If content was found
if ($robots_txt_content != null)
{
// Get all lines in the robots.txt-content that are adressed to our user-agent.
$applying_lines = $this->getApplyingLines($robots_txt_content, $user_agent_string);
// Get valid reg-expressions for the given disallow-pathes.
$non_follow_reg_exps = $this->buildRegExpressions($applying_lines, PHPCrawlerUtils::getRootUrl($Url->url_rebuild));
}
PHPCrawlerBenchmark::stop("processing_robots.txt");
return $non_follow_reg_exps;
} | php | {
"resource": ""
} |
q259743 | PHPCrawlerRobotsTxtParser.getApplyingLines | test | protected function getApplyingLines(&$robots_txt_content, $user_agent_string)
{
// Split the content into its lines
$robotstxt_lines = explode("\n", $robots_txt_content);
// Flag that will get TRUE if the loop over the lines gets
// into a section that applies to our user_agent_string
$matching_section = false;
// Flag that indicats if the loop is in a "agent-define-section"
// (the parts/blocks that contain the "User-agent"-lines.)
$agent_define_section = false;
// Flag that indicates if we have found a section that fits to our
// User-agent
$matching_section_found = false;
// Array to collect all the lines that applie to our user_agent
$applying_lines = array();
// Loop over the lines
$cnt = count($robotstxt_lines);
for ($x=0; $x<$cnt; $x++)
{
$robotstxt_lines[$x] = trim($robotstxt_lines[$x]);
// Check if a line begins with "User-agent"
if (preg_match("#^User-agent:# i", $robotstxt_lines[$x]))
{
// If a new "user-agent" section begins -> reset matching_section-flag
if ($agent_define_section == false)
{
$matching_section = false;
}
$agent_define_section = true; // Now we are in an agent-define-section
// The user-agent specified in the "User-agent"-line
preg_match("#^User-agent:[ ]*(.*)$# i", $robotstxt_lines[$x], $match);
$user_agent_section = trim($match[1]);
// if the specified user-agent in the line fits to our user-agent-String (* fits always)
// -> switch the flag "matching_section" to true
if ($user_agent_section == "*" || preg_match("#^".preg_quote($user_agent_section)."# i", $user_agent_string))
{
$matching_section = true;
$matching_section_found = true;
}
continue; // Don't do anything else with the "User-agent"-lines, just go on
}
else
{
// We are not in an agent-define-section (anymore)
$agent_define_section = false;
}
// If we are in a section that applies to our user_agent
// -> store the line.
if ($matching_section == true)
{
$applying_lines[] = $robotstxt_lines[$x];
}
// If we are NOT in a matching section (anymore) AND we've already found
// and parsed a matching section -> stop looking further (thats what RFC says)
if ($matching_section == false && $matching_section_found == true)
{
// break;
}
}
return $applying_lines;
} | php | {
"resource": ""
} |
q259744 | PHPCrawlerRobotsTxtParser.buildRegExpressions | test | protected function buildRegExpressions(&$applying_lines, $base_url)
{
// First, get all "Disallow:"-pathes
$disallow_pathes = array();
for ($x=0; $x<count($applying_lines); $x++)
{
if (preg_match("#^Disallow:# i", $applying_lines[$x]))
{
preg_match("#^Disallow:[ ]*(.*)#", $applying_lines[$x], $match);
$disallow_pathes[] = trim($match[1]);
}
}
// Works like this:
// The base-url is http://www.foo.com.
// The driective says: "Disallow: /bla/"
// This means: The nonFollowMatch is "#^http://www\.foo\.com/bla/#"
$normalized_base_url = PHPCrawlerUtils::normalizeURL($base_url);
$non_follow_expressions = array();
for ($x=0; $x<count($disallow_pathes); $x++)
{
// If the disallow-path is empty -> simply ignore it
if ($disallow_pathes[$x] == "") continue;
$non_follow_path_complpete = $normalized_base_url.substr($disallow_pathes[$x], 1); // "http://www.foo.com/bla/"
$non_follow_exp = preg_quote($non_follow_path_complpete, "#"); // "http://www\.foo\.com/bla/"
$non_follow_exp = "#^".$non_follow_exp."#"; // "#^http://www\.foo\.com/bla/#"
$non_follow_expressions[] = $non_follow_exp;
}
return $non_follow_expressions;
} | php | {
"resource": ""
} |
q259745 | PHPCrawlerRobotsTxtParser.getRobotsTxtContent | test | protected function getRobotsTxtContent(PHPCrawlerURLDescriptor $Url)
{
// Request robots-txt
$this->PageRequest->setUrl($Url);
$PageInfo = $this->PageRequest->sendRequest();
// Return content of the robots.txt-file if it was found, otherwie
// reutrn NULL
if ($PageInfo->http_status_code == 200)
{
return $PageInfo->content;
}
else
{
return null;
}
} | php | {
"resource": ""
} |
q259746 | PHPCrawlerRobotsTxtParser.getRobotsTxtURL | test | public static function getRobotsTxtURL(PHPCrawlerURLDescriptor $Url)
{
$url_parts = PHPCrawlerUtils::splitURL($Url->url_rebuild);
$robots_txt_url = $url_parts["protocol"].$url_parts["host"].":".$url_parts["port"] . "/robots.txt";
return new PHPCrawlerURLDescriptor($robots_txt_url);
} | php | {
"resource": ""
} |
q259747 | PHPCrawler.initCrawlerProcess | test | protected function initCrawlerProcess()
{
// Create working directory
$this->createWorkingDirectory();
// Setup url-cache
if ($this->url_cache_type == PHPCrawlerUrlCacheTypes::URLCACHE_SQLITE)
$this->LinkCache = new PHPCrawlerSQLiteURLCache($this->working_directory."urlcache.db3", true);
else
$this->LinkCache = new PHPCrawlerMemoryURLCache();
// Perge/cleanup SQLite-urlcache for resumed crawling-processes (only ONCE!)
if ($this->url_cache_type == PHPCrawlerUrlCacheTypes::URLCACHE_SQLITE && $this->urlcache_purged == false)
{
$this->LinkCache->purgeCache();
$this->urlcache_purged = true;
}
// Setup cookie-cache (use SQLite-cache if crawler runs multi-processed)
if ($this->url_cache_type == PHPCrawlerUrlCacheTypes::URLCACHE_SQLITE)
$this->CookieCache = new PHPCrawlerSQLiteCookieCache($this->working_directory."cookiecache.db3", true);
else $this->CookieCache = new PHPCrawlerMemoryCookieCache();
// ProcessCommunication
$this->ProcessCommunication = new PHPCrawlerProcessCommunication($this->crawler_uniqid, $this->multiprocess_mode, $this->working_directory, $this->resumtion_enabled);
// DocumentInfo-Queue
if ($this->multiprocess_mode == PHPCrawlerMultiProcessModes::MPMODE_PARENT_EXECUTES_USERCODE)
$this->DocumentInfoQueue = new PHPCrawlerDocumentInfoQueue($this->working_directory."doc_queue.db3", true);
// Set tmp-file for PageRequest
$this->PageRequest->setTmpFile($this->working_directory."phpcrawl_".getmypid().".tmp");
// Pass url-priorities to link-cache
$this->LinkCache->addLinkPriorities($this->link_priority_array);
// Pass base-URL to the UrlFilter
$this->UrlFilter->setBaseURL($this->starting_url);
// Add the starting-URL to the url-cache
$this->LinkCache->addUrl(new PHPCrawlerURLDescriptor($this->starting_url));
} | php | {
"resource": ""
} |
q259748 | PHPCrawler.goMultiProcessed | test | public function goMultiProcessed($process_count = 3, $multiprocess_mode = 1)
{
$this->multiprocess_mode = $multiprocess_mode;
// Check if fork is supported
if (!function_exists("pcntl_fork"))
{
throw new Exception("PHPCrawl running with multi processes not supported in this PHP-environment (function pcntl_fork() missing).".
"Try running from command-line (cli) and/or installing the PHP PCNTL-extension.");
}
if (!function_exists("sem_get"))
{
throw new Exception("PHPCrawl running with multi processes not supported in this PHP-environment (function sem_get() missing).".
"Try installing the PHP SEMAPHORE-extension.");
}
if (!function_exists("posix_kill"))
{
throw new Exception("PHPCrawl running with multi processes not supported in this PHP-environment (function posix_kill() missing).".
"Try installing the PHP POSIX-extension.");
}
if (!class_exists("PDO"))
{
throw new Exception("PHPCrawl running with multi processes not supported in this PHP-environment (class PDO missing).".
"Try installing the PHP PDO-extension.");
}
PHPCrawlerBenchmark::start("crawling_process");
// Set url-cache-type to sqlite.
$this->url_cache_type = PHPCrawlerUrlCacheTypes::URLCACHE_SQLITE;
// Init process
$this->initCrawlerProcess();
// Process robots.txt
if ($this->obey_robots_txt == true)
$this->processRobotsTxt();
// Fork off child-processes
$pids = array();
for($i=1; $i<=$process_count; $i++)
{
$pids[$i] = pcntl_fork();
if(!$pids[$i])
{
// Childprocess goes here
$this->is_chlid_process = true;
$this->child_process_number = $i;
$this->ProcessCommunication->registerChildPID(getmypid());
$this->startChildProcessLoop();
}
}
// Set flag "parent-process"
$this->is_parent_process = true;
// Determinate all child-PIDs
$this->child_pids = $this->ProcessCommunication->getChildPIDs($process_count);
// If crawler runs in MPMODE_PARENT_EXECUTES_USERCODE-mode -> start controller-loop
if ($this->multiprocess_mode == PHPCrawlerMultiProcessModes::MPMODE_PARENT_EXECUTES_USERCODE)
{
$this->starControllerProcessLoop();
}
// Wait for childs to finish
for ($i=1; $i<=$process_count; $i++)
{
pcntl_waitpid($pids[$i], $status, WUNTRACED);
}
// Get crawler-status (needed for process-report)
$this->crawlerStatus = $this->ProcessCommunication->getCrawlerStatus();
// Cleanup crawler
$this->cleanup();
PHPCrawlerBenchmark::stop("crawling_process");
} | php | {
"resource": ""
} |
q259749 | PHPCrawler.startChildProcessLoop | test | protected function startChildProcessLoop()
{
$this->initCrawlerProcess();
// Call overidable method initChildProcess()
$this->initChildProcess();
// Start benchmark (if single-processed)
if ($this->is_chlid_process == false)
{
PHPCrawlerBenchmark::start("crawling_process");
}
// Init vars
$stop_crawling = false;
// Main-Loop
while ($stop_crawling == false)
{
// Get next URL from cache
$UrlDescriptor = $this->LinkCache->getNextUrl();
// Process URL
if ($UrlDescriptor != null)
{
$stop_crawling = $this->processUrl($UrlDescriptor);
}
else
{
sleep(1);
}
if ($this->multiprocess_mode != PHPCrawlerMultiProcessModes::MPMODE_PARENT_EXECUTES_USERCODE)
{
// If there's nothing more to do
if ($this->LinkCache->containsURLs() == false)
{
$stop_crawling = true;
$this->ProcessCommunication->updateCrawlerStatus(null, PHPCrawlerAbortReasons::ABORTREASON_PASSEDTHROUGH);
}
// Check for abort form other processes
if ($this->checkForAbort() !== null) $stop_crawling = true;
}
}
// Loop enden gere. If child-process -> kill it
if ($this->is_chlid_process == true)
{
if ($this->multiprocess_mode == PHPCrawlerMultiProcessModes::MPMODE_PARENT_EXECUTES_USERCODE) return;
else exit;
}
$this->crawlerStatus = $this->ProcessCommunication->getCrawlerStatus();
// Cleanup crawler
$this->cleanup();
// Stop benchmark (if single-processed)
if ($this->is_chlid_process == false)
{
PHPCrawlerBenchmark::stop("crawling_process");
}
} | php | {
"resource": ""
} |
q259750 | PHPCrawler.checkForAbort | test | protected function checkForAbort()
{
PHPCrawlerBenchmark::start("checkning_for_abort");
$abort_reason = null;
// Get current status
$crawler_status = $this->ProcessCommunication->getCrawlerStatus();
// if crawlerstatus already marked for ABORT
if ($crawler_status->abort_reason !== null)
{
$abort_reason = $crawler_status->abort_reason;
}
// Check for reached limits
// If traffic-limit is reached
if ($this->traffic_limit > 0 && $crawler_status->bytes_received >= $this->traffic_limit)
$abort_reason = PHPCrawlerAbortReasons::ABORTREASON_TRAFFICLIMIT_REACHED;
// If document-limit is set
if ($this->document_limit > 0)
{
// If document-limit regards to received documetns
if ($this->only_count_received_documents == true && $crawler_status->documents_received >= $this->document_limit)
{
$abort_reason = PHPCrawlerAbortReasons::ABORTREASON_FILELIMIT_REACHED;
}
elseif ($this->only_count_received_documents == false && $crawler_status->links_followed >= $this->document_limit)
{
$abort_reason = PHPCrawlerAbortReasons::ABORTREASON_FILELIMIT_REACHED;
}
}
$this->ProcessCommunication->updateCrawlerStatus(null, $abort_reason);
PHPCrawlerBenchmark::stop("checkning_for_abort");
return $abort_reason;
} | php | {
"resource": ""
} |
q259751 | PHPCrawler.createWorkingDirectory | test | protected function createWorkingDirectory()
{
$this->working_directory = $this->working_base_directory."phpcrawl_tmp_".$this->crawler_uniqid.DIRECTORY_SEPARATOR;
// Check if writable
if (!is_writeable($this->working_base_directory))
{
throw new Exception("Error creating working directory '".$this->working_directory."'");
}
// Create dir
if (!file_exists($this->working_directory))
{
mkdir($this->working_directory);
}
} | php | {
"resource": ""
} |
q259752 | PHPCrawler.getProcessReport | test | public function getProcessReport()
{
// Get current crawler-Status
$CrawlerStatus = $this->crawlerStatus;
// Create report
$Report = new PHPCrawlerProcessReport();
$Report->links_followed = $CrawlerStatus->links_followed;
$Report->files_received = $CrawlerStatus->documents_received;
$Report->bytes_received = $CrawlerStatus->bytes_received;
$Report->process_runtime = PHPCrawlerBenchmark::getElapsedTime("crawling_process");
if ($Report->process_runtime > 0)
$Report->data_throughput = $Report->bytes_received / $Report->process_runtime;
// Process abort-reason
$Report->abort_reason = $CrawlerStatus->abort_reason;
if ($CrawlerStatus->abort_reason == PHPCrawlerAbortReasons::ABORTREASON_TRAFFICLIMIT_REACHED)
$Report->traffic_limit_reached = true;
if ($CrawlerStatus->abort_reason == PHPCrawlerAbortReasons::ABORTREASON_FILELIMIT_REACHED)
$Report->file_limit_reached = true;
if ($CrawlerStatus->abort_reason == PHPCrawlerAbortReasons::ABORTREASON_USERABORT)
$Report->user_abort = true;
// Peak memory-usage
if (function_exists("memory_get_peak_usage"))
$Report->memory_peak_usage = memory_get_peak_usage(true);
return $Report;
} | php | {
"resource": ""
} |
q259753 | PHPCrawler.addLinkPriority | test | function addLinkPriority($regex, $level)
{
$check = PHPCrawlerUtils::checkRegexPattern($regex); // Check pattern
if ($check == true && preg_match("/^[0-9]*$/", $level))
{
$c = count($this->link_priority_array);
$this->link_priority_array[$c]["match"] = trim($regex);
$this->link_priority_array[$c]["level"] = trim($level);
return true;
}
else return false;
} | php | {
"resource": ""
} |
q259754 | PHPCrawler.setFollowMode | test | public function setFollowMode($follow_mode)
{
// Check mode
if (!preg_match("/^[0-3]{1}$/", $follow_mode)) return false;
$this->UrlFilter->general_follow_mode = $follow_mode;
return true;
} | php | {
"resource": ""
} |
q259755 | PHPCrawler.setTrafficLimit | test | public function setTrafficLimit($bytes, $complete_requested_files = true)
{
if (preg_match("#^[0-9]*$#", $bytes))
{
$this->traffic_limit = $bytes;
return true;
}
else return false;
} | php | {
"resource": ""
} |
q259756 | PHPCrawler.setWorkingDirectory | test | public function setWorkingDirectory($directory)
{
if (is_writeable($this->working_base_directory))
{
$this->working_base_directory = $directory;
return true;
}
else return false;
} | php | {
"resource": ""
} |
q259757 | PHPCrawler.setProxy | test | public function setProxy($proxy_host, $proxy_port, $proxy_username = null, $proxy_password = null)
{
$this->PageRequest->setProxy($proxy_host, $proxy_port, $proxy_username, $proxy_password);
} | php | {
"resource": ""
} |
q259758 | PHPCrawler.setConnectionTimeout | test | public function setConnectionTimeout($timeout)
{
if (preg_match("#[0-9]+#", $timeout))
{
$this->PageRequest->socketConnectTimeout = $timeout;
return true;
}
else
{
return false;
}
} | php | {
"resource": ""
} |
q259759 | PHPCrawler.setStreamTimeout | test | public function setStreamTimeout($timeout)
{
if (preg_match("#[0-9]+#", $timeout))
{
$this->PageRequest->socketReadTimeout = $timeout;
return true;
}
else
{
return false;
}
} | php | {
"resource": ""
} |
q259760 | PHPCrawler.resume | test | public function resume($crawler_id)
{
if ($this->resumtion_enabled == false)
throw new Exception("Resumption was not enalbled, call enableResumption() before calling the resume()-method!");
// Adobt crawler-id
$this->crawler_uniqid = $crawler_id;
if (!file_exists($this->working_base_directory."phpcrawl_tmp_".$this->crawler_uniqid.DIRECTORY_SEPARATOR))
{
throw new Exception("Couldn't find any previous aborted crawling-process with crawler-id '".$this->crawler_uniqid."'");
}
$this->createWorkingDirectory();
// Unlinks pids file in working-dir (because all PIDs will change in new process)
if (file_exists($this->working_directory."pids")) unlink($this->working_directory."pids");
} | php | {
"resource": ""
} |
q259761 | PHPCrawlerURLFilter.setBaseURL | test | public function setBaseURL($starting_url)
{
$this->starting_url = $starting_url;
// Parts of the starting-URL
$this->starting_url_parts = PHPCrawlerUtils::splitURL($starting_url);
} | php | {
"resource": ""
} |
q259762 | PHPCrawlerURLFilter.keepRedirectUrls | test | public static function keepRedirectUrls(PHPCrawlerDocumentInfo $DocumentInfo)
{
$cnt = count($DocumentInfo->links_found_url_descriptors);
for ($x=0; $x<$cnt; $x++)
{
if ($DocumentInfo->links_found_url_descriptors[$x]->is_redirect_url == false)
{
$DocumentInfo->links_found_url_descriptors[$x] = null;
}
}
} | php | {
"resource": ""
} |
q259763 | PHPCrawlerURLFilter.urlMatchesRules | test | protected function urlMatchesRules(PHPCrawlerURLDescriptor $url)
{
// URL-parts of the URL to check against the filter-rules
$url_parts = PHPCrawlerUtils::splitURL($url->url_rebuild);
// Kick out all links that r NOT of protocol "http" or "https"
if ($url_parts["protocol"] != "http://" && $url_parts["protocol"] != "https://")
{
return false;
}
// If meta-tag "robots"->"nofollow" is present and obey_nofollow_tags is TRUE -> always kick out URL
if ($this->obey_nofollow_tags == true &&
isset($this->CurrentDocumentInfo->meta_attributes["robots"]) &&
preg_match("#nofollow# i", $this->CurrentDocumentInfo->meta_attributes["robots"]))
{
return false;
}
// If linkcode contains "rel='nofollow'" and obey_nofollow_tags is TRUE -> always kick out URL
if ($this->obey_nofollow_tags == true)
{
if (preg_match("#^<[^>]*rel\s*=\s*(?|\"\s*nofollow\s*\"|'\s*nofollow\s*'|\s*nofollow\s*)[^>]*>#", $url->linkcode))
{
return false;
}
}
// Filter URLs to other domains if wanted
if ($this->general_follow_mode >= 1)
{
if ($url_parts["domain"] != $this->starting_url_parts["domain"]) return false;
}
// Filter URLs to other hosts if wanted
if ($this->general_follow_mode >= 2)
{
// Ignore "www." at the beginning of the host, because "www.foo.com" is the same host as "foo.com"
if (preg_replace("#^www\.#", "", $url_parts["host"]) != preg_replace("#^www\.#", "", $this->starting_url_parts["host"]))
return false;
}
// Filter URLs leading path-up if wanted
if ($this->general_follow_mode == 3)
{
if ($url_parts["protocol"] != $this->starting_url_parts["protocol"] ||
preg_replace("#^www\.#", "", $url_parts["host"]) != preg_replace("#^www\.#", "", $this->starting_url_parts["host"]) ||
substr($url_parts["path"], 0, strlen($this->starting_url_parts["path"])) != $this->starting_url_parts["path"])
{
return false;
}
}
// Filter URLs by url_filter_rules
for ($x=0; $x<count($this->url_filter_rules); $x++)
{
if (preg_match($this->url_filter_rules[$x], $url->url_rebuild)) return false;
}
// Filter URLs by url_follow_rules
if (count($this->url_follow_rules) > 0)
{
$match_found = false;
for ($x=0; $x<count($this->url_follow_rules); $x++)
{
if (preg_match($this->url_follow_rules[$x], $url->url_rebuild))
{
$match_found = true;
break;
}
}
if ($match_found == false) return false;
}
return true;
} | php | {
"resource": ""
} |
q259764 | PHPCrawlerURLFilter.addURLFilterRule | test | public function addURLFilterRule($regex)
{
$check = PHPCrawlerUtils::checkRegexPattern($regex); // Check pattern
if ($check == true)
{
$this->url_filter_rules[] = trim($regex);
}
return $check;
} | php | {
"resource": ""
} |
q259765 | PHPCrawlerURLFilter.addURLFilterRules | test | public function addURLFilterRules($regex_array)
{
$cnt = count($regex_array);
for ($x=0; $x<$cnt; $x++)
{
$this->addURLFilterRule($regex_array[$x]);
}
} | php | {
"resource": ""
} |
q259766 | PHPCrawlerSQLiteURLCache.markUrlAsFollowed | test | public function markUrlAsFollowed(PHPCrawlerURLDescriptor $UrlDescriptor)
{
PHPCrawlerBenchmark::start("marking_url_as_followes");
$hash = md5($UrlDescriptor->url_rebuild);
$this->PDO->exec("UPDATE urls SET processed = 1, in_process = 0 WHERE distinct_hash = '".$hash."';");
PHPCrawlerBenchmark::stop("marking_url_as_followes");
} | php | {
"resource": ""
} |
q259767 | PHPCrawlerSQLiteURLCache.containsURLs | test | public function containsURLs()
{
PHPCrawlerBenchmark::start("checking_for_urls_in_cache");
$Result = $this->PDO->query("SELECT id FROM urls WHERE processed = 0 OR in_process = 1 LIMIT 1;");
$has_columns = $Result->fetchColumn();
$Result->closeCursor();
PHPCrawlerBenchmark::stop("checking_for_urls_in_cache");
if ($has_columns != false)
{
return true;
}
else return false;
} | php | {
"resource": ""
} |
q259768 | PHPCrawlerMemoryURLCache.getAllURLs | test | public function getAllURLs()
{
$URLs = array();
@reset($this->urls);
while (list($pri_lvl) = @each($this->urls))
{
$cnt = count($this->urls[$pri_lvl]);
for ($x=0; $x<$cnt; $x++)
{
$URLs[] = &$this->urls[$pri_lvl][$x];
}
}
return $URLs;
} | php | {
"resource": ""
} |
q259769 | PHPCrawlerMemoryURLCache.addURLs | test | public function addURLs($urls)
{
//PHPCrawlerBenchmark::start("caching_urls");
$cnt = count($urls);
for ($x=0; $x<$cnt; $x++)
{
if ($urls[$x] != null)
{
$this->addURL($urls[$x]);
}
}
//PHPCrawlerBenchmark::stop("caching_urls");
} | php | {
"resource": ""
} |
q259770 | PHPCrawlerBenchmark.start | test | public static function start($identifier, $temporary_benchmark = false)
{
self::$benchmark_starttimes[$identifier] = self::getmicrotime();
if (isset(self::$benchmark_startcount[$identifier]))
self::$benchmark_startcount[$identifier] = self::$benchmark_startcount[$identifier] + 1;
else self::$benchmark_startcount[$identifier] = 1;
if ($temporary_benchmark == true)
{
self::$temporary_benchmarks[$identifier] = true;
}
} | php | {
"resource": ""
} |
q259771 | PHPCrawlerBenchmark.stop | test | public static function stop($identifier)
{
if (isset(self::$benchmark_starttimes[$identifier]))
{
$elapsed_time = self::getmicrotime() - self::$benchmark_starttimes[$identifier];
if (isset(self::$benchmark_results[$identifier])) self::$benchmark_results[$identifier] += $elapsed_time;
else self::$benchmark_results[$identifier] = $elapsed_time;
}
} | php | {
"resource": ""
} |
q259772 | PHPCrawlerBenchmark.resetAll | test | public static function resetAll($retain_benchmarks = array())
{
// If no benchmarks should be retained
if (count($retain_benchmarks) == 0)
{
self::$benchmark_results = array();
return;
}
// Else reset all benchmarks BUT the retain_benachmarks
@reset(self::$benchmark_results);
while (list($identifier) = @each(self::$benchmark_results))
{
if (!in_array($identifier, $retain_benchmarks))
{
self::$benchmark_results[$identifier] = 0;
}
}
} | php | {
"resource": ""
} |
q259773 | PHPCrawlerBenchmark.getAllBenchmarks | test | public static function getAllBenchmarks()
{
$benchmarks = array();
@reset(self::$benchmark_results);
while (list($identifier, $elapsed_time) = @each(self::$benchmark_results))
{
if (!isset(self::$temporary_benchmarks[$identifier])) $benchmarks[$identifier] = $elapsed_time;
}
return $benchmarks;
} | php | {
"resource": ""
} |
q259774 | PHPCrawlerBenchmark.getmicrotime | test | public static function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
} | php | {
"resource": ""
} |
q259775 | PHPCrawlerSQLiteCookieCache.openConnection | test | protected function openConnection($create_tables = false)
{
//PHPCrawlerBenchmark::start("Connecting to SQLite-cache-db");
// Open sqlite-file
try
{
$this->PDO = new PDO("sqlite:".$this->sqlite_db_file);
}
catch (Exception $e)
{
throw new Exception("Error creating SQLite-cache-file, ".$e->getMessage().", try installing sqlite3-extension for PHP.");
}
$this->PDO->exec("PRAGMA journal_mode = OFF");
$this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->PDO->setAttribute(PDO::ATTR_TIMEOUT, 100);
if ($create_tables == true)
{
// Create url-table (if not exists)
$this->PDO->exec("CREATE TABLE IF NOT EXISTS cookies (id integer PRIMARY KEY AUTOINCREMENT,
cookie_hash TEXT UNIQUE,
source_domain TEXT,
source_url TEXT,
name TEXT,
value TEXT,
domain TEXT,
path TEXT,
expires TEXT,
expire_timestamp INTEGER,
cookie_send_time INTEGER);");
// Create indexes (seems that indexes make the whole thingy slower)
$this->PDO->exec("CREATE INDEX IF NOT EXISTS cookie_hash ON cookies (cookie_hash);");
$this->PDO->exec("ANALYZE;");
}
//PHPCrawlerBenchmark::stop("Connecting to SQLite-cache-db");
} | php | {
"resource": ""
} |
q259776 | PHPCrawlerURLCacheBase.getDistinctURLHash | test | protected function getDistinctURLHash(PHPCrawlerURLDescriptor $UrlDescriptor)
{
if ($this->url_distinct_property == self::URLHASH_URL)
return md5($UrlDescriptor->url_rebuild);
elseif ($this->url_distinct_property == self::URLHASH_RAWLINK)
return md5($UrlDescriptor->link_raw);
else
return null;
} | php | {
"resource": ""
} |
q259777 | PHPCrawlerURLCacheBase.getUrlPriority | test | protected function getUrlPriority($url)
{
$cnt = count($this->url_priorities);
for ($x=0; $x<$cnt; $x++)
{
if (preg_match($this->url_priorities[$x]["match"], $url))
{
return $this->url_priorities[$x]["level"];
}
}
return 0;
} | php | {
"resource": ""
} |
q259778 | PHPCrawlerURLCacheBase.addLinkPriority | test | public function addLinkPriority($regex, $level)
{
$c = count($this->url_priorities);
$this->url_priorities[$c]["match"] = trim($regex);
$this->url_priorities[$c]["level"] = trim($level);
// Sort url-priortie-array so that high priority-levels come firts.
PHPCrawlerUtils::sort2dArray($this->url_priorities, "level", SORT_DESC);
} | php | {
"resource": ""
} |
q259779 | PHPCrawlerURLCacheBase.addLinkPriorities | test | public function addLinkPriorities($priority_array)
{
for ($x=0; $x<count($priority_array); $x++)
{
$this->addLinkPriority($priority_array[$x]["match"], $priority_array[$x]["level"]);
}
} | php | {
"resource": ""
} |
q259780 | PHPCrawlerDocumentInfoQueue.addDocumentInfo | test | public function addDocumentInfo(PHPCrawlerDocumentInfo $DocInfo)
{
// If queue is full -> wait a little
while ($this->getDocumentInfoCount() >= $this->queue_max_size)
{
sleep(0.5);
}
$this->createPreparedStatements();
$ser = serialize($DocInfo);
$this->PDO->exec("BEGIN EXCLUSIVE TRANSACTION");
$this->prepared_insert_statement->bindParam(1, $ser, PDO::PARAM_LOB);
$this->prepared_insert_statement->execute();
$this->prepared_select_statement->closeCursor();
$this->PDO->exec("COMMIT");
} | php | {
"resource": ""
} |
q259781 | PHPCrawlerDocumentInfoQueue.getNextDocumentInfo | test | public function getNextDocumentInfo()
{
$this->createPreparedStatements();
$this->prepared_select_statement->execute();
$this->prepared_select_statement->bindColumn("document_info", $doc_info, PDO::PARAM_LOB);
$this->prepared_select_statement->bindColumn("id", $id);
$row = $this->prepared_select_statement->fetch(PDO::FETCH_BOUND);
$this->prepared_select_statement->closeCursor();
if ($id == null)
{
return null;
}
$this->PDO->exec("DELETE FROM document_infos WHERE id = ".$id.";");
$DocInfo = unserialize($doc_info);
return $DocInfo;
} | php | {
"resource": ""
} |
q259782 | PHPCrawlerUrlPartsDescriptor.fromURL | test | public static function fromURL($url)
{
$parts = PHPCrawlerUtils::splitURL($url);
$tmp = new PHPCrawlerUrlPartsDescriptor();
$tmp->protocol = $parts["protocol"];
$tmp->host = $parts["host"];
$tmp->path = $parts["path"];
$tmp->file = $parts["file"];
$tmp->domain = $parts["domain"];
$tmp->port = $parts["port"];
$tmp->auth_username = $parts["auth_username"];
$tmp->auth_password = $parts["auth_password"];
return $tmp;
} | php | {
"resource": ""
} |
q259783 | PHPCrawlerLinkFinder.setSourceUrl | test | public function setSourceUrl(PHPCrawlerURLDescriptor $SourceUrl)
{
$this->SourceUrl = $SourceUrl;
$this->baseUrlParts = PHPCrawlerUrlPartsDescriptor::fromURL($SourceUrl->url_rebuild);
} | php | {
"resource": ""
} |
q259784 | PHPCrawlerLinkFinder.findRedirectLinkInHeader | test | protected function findRedirectLinkInHeader(&$http_header)
{
PHPCrawlerBenchmark::start("checking_for_redirect_link");
// Get redirect-URL or link from header
$redirect_link = PHPCrawlerUtils::getRedirectURLFromHeader($http_header);
// Add redirect-URL to linkcache
if ($redirect_link != null)
{
// Rebuild URL
$url_rebuild = PHPCrawlerUtils::buildURLFromLink($redirect_link, $this->baseUrlParts);
// Add URL to cache
$UrlDescriptor = new PHPCrawlerURLDescriptor($url_rebuild, $redirect_link, "", "", $this->SourceUrl->url_rebuild);
$UrlDescriptor->is_redirect_url = true;
$this->LinkCache->addURL($UrlDescriptor);
}
PHPCrawlerBenchmark::stop("checking_for_redirect_link");
} | php | {
"resource": ""
} |
q259785 | PHPCrawlerUserSendDataCache.addPostData | test | public function addPostData($url_regex, $post_data_array)
{
// Check regex
$regex_okay = PHPCrawlerUtils::checkRegexPattern($url_regex);
if ($regex_okay == true)
{
@reset($post_data_array);
while (list($key, $value) = @each($post_data_array))
{
// Add data to post_data-array
$tmp = array();
$tmp["url_regex"] = $url_regex;
$tmp["key"] = $key;
$tmp["value"] = $value;
$this->post_data[] = $tmp;
}
return true;
}
else return false;
} | php | {
"resource": ""
} |
q259786 | PHPCrawlerProcessCommunication.updateCrawlerStatus | test | public function updateCrawlerStatus($PageInfo, $abort_reason = null, $first_content_url = null)
{
PHPCrawlerBenchmark::start("updating_crawler_status");
// Set semaphore if crawler is multiprocessed
if ($this->multiprocess_mode == PHPCrawlerMultiProcessModes::MPMODE_CHILDS_EXECUTES_USERCODE || $this->resumtion_enabled == true)
{
$sem_key = sem_get($this->crawler_uniqid);
sem_acquire($sem_key);
}
// Get current Status
$crawler_status = $this->getCrawlerStatus();
// Update status
if ($PageInfo != null)
{
// Increase number of followed links
$crawler_status->links_followed++;
// Increase documents_received-counter
if ($PageInfo->received == true) $crawler_status->documents_received++;
// Increase bytes-counter
$crawler_status->bytes_received += $PageInfo->bytes_received;
}
// Set abortreason
if ($abort_reason !== null) $crawler_status->abort_reason = $abort_reason;
// Set first_content_url
if ($first_content_url !== null) $crawler_status->first_content_url = $first_content_url;
// Write crawler-status back
$this->setCrawlerStatus($crawler_status);
// Remove semaphore if crawler is multiprocessed
if ($this->multiprocess_mode == PHPCrawlerMultiProcessModes::MPMODE_CHILDS_EXECUTES_USERCODE || $this->resumtion_enabled == true)
{
sem_release($sem_key);
}
PHPCrawlerBenchmark::stop("updating_crawler_status");
} | php | {
"resource": ""
} |
q259787 | PHPCrawlerProcessCommunication.registerChildPID | test | public function registerChildPID($pid)
{
$sem_key = sem_get($this->crawler_uniqid);
sem_acquire($sem_key);
file_put_contents($this->working_directory."pids", $pid."\n", FILE_APPEND);
sem_release($sem_key);
} | php | {
"resource": ""
} |
q259788 | PHPCrawlerProcessCommunication.getChildPIDs | test | public function getChildPIDs($process_count = null)
{
$child_pids = array();
$try = true;
while ($try == true)
{
if (file_exists($this->working_directory."pids"))
{
$ct = file_get_contents($this->working_directory."pids");
$child_pids = preg_split("#\n#", $ct, -1, PREG_SPLIT_NO_EMPTY);
if ($process_count == null) $try = false;
if (count($child_pids) == $process_count) $try = false;
}
sleep(0.2);
}
return $child_pids;
} | php | {
"resource": ""
} |
q259789 | PHPCrawlerProcessCommunication.killChildProcesses | test | public function killChildProcesses()
{
$child_pids = $this->getChildPIDs();
for ($x=0; $x<count($child_pids); $x++)
{
posix_kill($child_pids[$x], SIGKILL);
}
} | php | {
"resource": ""
} |
q259790 | PHPCrawlerDNSCache.getIP | test | public function getIP($hostname)
{
// If host already was queried
if (isset($this->host_ip_array[$hostname]))
{
return $this->host_ip_array[$hostname];
}
// Else do DNS-query
else
{
$ip = gethostbyname($hostname);
$this->host_ip_array[$hostname] = $ip;
return $ip;
}
} | php | {
"resource": ""
} |
q259791 | PHPCrawlerDNSCache.urlHostInCache | test | public function urlHostInCache(PHPCrawlerURLDescriptor $URL)
{
$url_parts = PHPCrawlerUtils::splitURL($URL->url_rebuild);
return $this->hostInCache($url_parts["host"]);
} | php | {
"resource": ""
} |
q259792 | ExpressionTraverser.removeVisitor | test | public function removeVisitor(ExpressionVisitor $visitor)
{
while (false !== ($key = array_search($visitor, $this->visitors, true))) {
unset($this->visitors[$key]);
}
$this->visitors = array_values($this->visitors);
} | php | {
"resource": ""
} |
q259793 | ExpressionTraverser.traverse | test | public function traverse(Expression $expr)
{
// Do one full traversal per visitor. If any of the visitors removes
// the expression entirely, subsequent visitors are not invoked.
foreach ($this->visitors as $visitor) {
$expr = $this->traverseForVisitor($expr, $visitor);
if (!$expr) {
return null;
}
}
return $expr;
} | php | {
"resource": ""
} |
q259794 | Expr.filter | test | public static function filter($collection, Expression $expr)
{
if (is_array($collection)) {
return array_filter($collection, array($expr, 'evaluate'));
}
if (!($collection instanceof Traversable && $collection instanceof ArrayAccess)) {
throw new InvalidArgumentException(sprintf(
'Expected an array or an instance of Traversable and ArrayAccess. Got: %s',
is_object($collection) ? get_class($collection) : gettype($collection)
));
}
$clone = clone $collection;
foreach ($collection as $key => $value) {
if (!$expr->evaluate($value)) {
unset($clone[$key]);
}
}
return $clone;
} | php | {
"resource": ""
} |
q259795 | Expr.method | test | public static function method($methodName, $args)
{
$args = func_get_args();
$methodName = array_shift($args);
$expr = array_pop($args);
return new Method($methodName, $args, $expr);
} | php | {
"resource": ""
} |
q259796 | StringUtil.formatValue | test | public static function formatValue($value)
{
if (null === $value) {
return 'null';
}
if (true === $value) {
return 'true';
}
if (false === $value) {
return 'false';
}
if (is_string($value)) {
return '"'.$value.'"';
}
if (is_object($value)) {
return 'object';
}
if (is_array($value)) {
return 'array';
}
return (string) $value;
} | php | {
"resource": ""
} |
q259797 | StringUtil.formatValues | test | public static function formatValues(array $values)
{
foreach ($values as $key => $value) {
$values[$key] = self::formatValue($value);
}
return $values;
} | php | {
"resource": ""
} |
q259798 | Configure.write | test | public static function write($config, $value = null)
{
if (!is_array($config)) {
$config = [$config => $value];
}
foreach ($config as $name => $value) {
static::$values = Hash::insert(static::$values, $name, $value);
}
if (isset($config['debug'])) {
if (static::$hasIniSet === null) {
static::$hasIniSet = function_exists('ini_set');
}
if (static::$hasIniSet) {
ini_set('display_errors', $config['debug'] ? 1 : 0);
}
}
return true;
} | php | {
"resource": ""
} |
q259799 | Configure.consume | test | public static function consume($var)
{
if (strpos($var, '.') === false) {
if (!isset(static::$values[$var])) {
return null;
}
$value = static::$values[$var];
unset(static::$values[$var]);
return $value;
}
$value = Hash::get(static::$values, $var);
static::delete($var);
return $value;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.