diff --git a/.gitignore b/.gitignore deleted file mode 100644 index f31342f5..00000000 --- a/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.buildpath -.project -.settings -.gitignore.swp -plugins/* diff --git a/PHPHtmlParser/Content.php b/PHPHtmlParser/Content.php new file mode 100644 index 00000000..aa0dfe52 --- /dev/null +++ b/PHPHtmlParser/Content.php @@ -0,0 +1,252 @@ +'; + protected $slash = " />\r\n\t"; + protected $attr = ' >'; + + /** + * Content constructor. + * + * @param $content + */ + public function __construct($content) + { + $this->content = $content; + $this->size = strlen($content); + $this->pos = 0; + } + + /** + * Returns the current position of the content. + * + * @return int + */ + public function getPosition() + { + return $this->pos; + } + + /** + * Gets the current character we are at. + * + * @param int $char + * @return string + */ + public function char($char = null) + { + $pos = $this->pos; + if ( ! is_null($char)) { + $pos = $char; + } + + if ( ! isset($this->content[$pos])) { + return ''; + } + + return $this->content[$pos]; + } + + /** + * Moves the current position forward. + * + * @param int $count + * @return $this + */ + public function fastForward($count) + { + $this->pos += $count; + + return $this; + } + + /** + * Moves the current position backward. + * + * @param int $count + * @return $this + */ + public function rewind($count) + { + $this->pos -= $count; + if ($this->pos < 0) { + $this->pos = 0; + } + + return $this; + } + + /** + * Copy the content until we find the given string. + * + * @param string $string + * @param bool $char + * @param bool $escape + * @return string + */ + public function copyUntil($string, $char = false, $escape = false) + { + if ($this->pos >= $this->size) { + // nothing left + return ''; + } + + if ($escape) { + $position = $this->pos; + $found = false; + while ( ! $found) { + $position = strpos($this->content, $string, $position); + if ($position === false) { + // reached the end + $found = true; + continue; + } + + if ($this->char($position - 1) == '\\') { + // this character is escaped + ++$position; + continue; + } + + $found = true; + } + } elseif ($char) { + $position = strcspn($this->content, $string, $this->pos); + $position += $this->pos; + } else { + $position = strpos($this->content, $string, $this->pos); + } + + if ($position === false) { + // could not find character, just return the remaining of the content + $return = substr($this->content, $this->pos, $this->size - $this->pos); + $this->pos = $this->size; + + return $return; + } + + if ($position == $this->pos) { + // we are at the right place + return ''; + } + + $return = substr($this->content, $this->pos, $position - $this->pos); + // set the new position + $this->pos = $position; + + return $return; + } + + /** + * Copies the content until the string is found and return it + * unless the 'unless' is found in the substring. + * + * @param string $string + * @param string $unless + * @return string + */ + public function copyUntilUnless($string, $unless) + { + $lastPos = $this->pos; + $this->fastForward(1); + $foundString = $this->copyUntil($string, true, true); + + $position = strcspn($foundString, $unless); + if ($position == strlen($foundString)) { + return $string.$foundString; + } + // rewind changes and return nothing + $this->pos = $lastPos; + + return ''; + } + + /** + * Copies the content until it reaches the token string., + * + * @param string $token + * @param bool $char + * @param bool $escape + * @return string + * @uses $this->copyUntil() + */ + public function copyByToken($token, $char = false, $escape = false) + { + $string = $this->$token; + + return $this->copyUntil($string, $char, $escape); + } + + /** + * Skip a given set of characters. + * + * @param string $string + * @param bool $copy + * @return $this|string + */ + public function skip($string, $copy = false) + { + $len = strspn($this->content, $string, $this->pos); + + // make it chainable if they don't want a copy + $return = $this; + if ($copy) { + $return = substr($this->content, $this->pos, $len); + } + + // update the position + $this->pos += $len; + + return $return; + } + + /** + * Skip a given token of pre-defined characters. + * + * @param string $token + * @param bool $copy + * @return null|string + * @uses $this->skip() + */ + public function skipByToken($token, $copy = false) + { + $string = $this->$token; + + return $this->skip($string, $copy); + } +} diff --git a/PHPHtmlParser/Curl.php b/PHPHtmlParser/Curl.php new file mode 100644 index 00000000..a6fcb95f --- /dev/null +++ b/PHPHtmlParser/Curl.php @@ -0,0 +1,41 @@ +root->innerHtml(); + } + + /** + * A simple wrapper around the root node. + * + * @param string $name + * @return mixed + */ + public function __get($name) + { + return $this->root->$name; + } + + /** + * Attempts to load the dom from any resource, string, file, or URL. + * + * @param string $str + * @param array $options + * @return $this + */ + public function load($str, $options = []) + { + // check if it's a file + if (strpos($str, "\n") === false && is_file($str)) { + return $this->loadFromFile($str, $options); + } + // check if it's a url + if (preg_match("/^https?:\/\//i", $str)) { + return $this->loadFromUrl($str, $options); + } + + return $this->loadStr($str, $options); + } + + /** + * Loads the dom from a document file/url + * + * @param string $file + * @param array $options + * @return $this + */ + public function loadFromFile($file, $options = []) + { + return $this->loadStr(file_get_contents($file), $options); + } + + /** + * Use a curl interface implementation to attempt to load + * the content from a url. + * + * @param string $url + * @param array $options + * @param CurlInterface $curl + * @return $this + */ + public function loadFromUrl($url, $options = [], CurlInterface $curl = null) + { + if (is_null($curl)) { + // use the default curl interface + $curl = new Curl; + } + $content = $curl->get($url); + + return $this->loadStr($content, $options); + } + + /** + * Parsers the html of the given string. Used for load(), loadFromFile(), + * and loadFromUrl(). + * + * @param string $str + * @param array $option + * @return $this + */ + public function loadStr($str, $option) + { + $this->options = new Options; + $this->options->setOptions($this->globalOptions) + ->setOptions($option); + + $this->rawSize = strlen($str); + $this->raw = $str; + + $html = $this->clean($str); + + $this->size = strlen($str); + $this->content = new Content($html); + + $this->parse(); + $this->detectCharset(); + + return $this; + } + + /** + * Sets a global options array to be used by all load calls. + * + * @param array $options + * @return $this + */ + public function setOptions(array $options) + { + $this->globalOptions = $options; + + return $this; + } + + /** + * Find elements by css selector on the root node. + * + * @param string $selector + * @param int $nth + * @return array + */ + public function find($selector, $nth = null) + { + $this->isLoaded(); + + return $this->root->find($selector, $nth); + } + + /** + * Adds the tag (or tags in an array) to the list of tags that will always + * be self closing. + * + * @param string|array $tag + * @return $this + */ + public function addSelfClosingTag($tag) + { + if ( ! is_array($tag)) { + $tag = [$tag]; + } + foreach ($tag as $value) { + $this->selfClosing[] = $value; + } + + return $this; + } + + /** + * Removes the tag (or tags in an array) from the list of tags that will + * always be self closing. + * + * @param string|array $tag + * @return $this + */ + public function removeSelfClosingTag($tag) + { + if ( ! is_array($tag)) { + $tag = [$tag]; + } + $this->selfClosing = array_diff($this->selfClosing, $tag); + + return $this; + } + + /** + * Sets the list of self closing tags to empty. + * + * @return $this + */ + public function clearSelfClosingTags() + { + $this->selfClosing = []; + + return $this; + } + + /** + * Simple wrapper function that returns the first child. + * + * @return \PHPHtmlParser\Dom\AbstractNode + */ + public function firstChild() + { + $this->isLoaded(); + + return $this->root->firstChild(); + } + + /** + * Simple wrapper function that returns the last child. + * + * @return \PHPHtmlParser\Dom\AbstractNode + */ + public function lastChild() + { + $this->isLoaded(); + + return $this->root->lastChild(); + } + + /** + * Simple wrapper function that returns an element by the + * id. + * + * @param string $id + * @return \PHPHtmlParser\Dom\AbstractNode + */ + public function getElementById($id) + { + $this->isLoaded(); + + return $this->find('#'.$id, 0); + } + + /** + * Simple wrapper function that returns all elements by + * tag name. + * + * @param string $name + * @return array + */ + public function getElementsByTag($name) + { + $this->isLoaded(); + + return $this->find($name); + } + + /** + * Simple wrapper function that returns all elements by + * class name. + * + * @param string $class + * @return array + */ + public function getElementsByClass($class) + { + $this->isLoaded(); + + return $this->find('.'.$class); + } + + /** + * Checks if the load methods have been called. + * + * @throws NotLoadedException + */ + protected function isLoaded() + { + if (is_null($this->content)) { + throw new NotLoadedException('Content is not loaded!'); + } + } + + /** + * Cleans the html of any none-html information. + * + * @param string $str + * @return string + */ + protected function clean($str) + { + if ($this->options->get('cleanupInput') != true) { + // skip entire cleanup step + return $str; + } + + // remove white space before closing tags + $str = mb_eregi_replace("'\s+>", "'>", $str); + $str = mb_eregi_replace('"\s+>', '">', $str); + + // clean out the \n\r + $replace = ' '; + if ($this->options->get('preserveLineBreaks')) { + $replace = ' '; + } + $str = str_replace(["\r\n", "\r", "\n"], $replace, $str); + + // strip the doctype + $str = mb_eregi_replace("", '', $str); + + // strip out comments + $str = mb_eregi_replace("", '', $str); + + // strip out cdata + $str = mb_eregi_replace("", '', $str); + + // strip out "; - return; - } - - $sql = "select ds.* ,d.domain - from dirsubmitinfo ds,directories d - where ds.directory_id=d.id - and ds.website_id={$searchInfo['website_id']} and ds.active=0 - order by submit_time"; - $reportList = $this->db->select($sql); - $this->set('list', $reportList); - $this->render('directory/generatesubmission'); - } - - function deleteSubmissionReports($dirSubId){ - - $dirSubId = intval($dirSubId); - $sql = "delete from dirsubmitinfo where id=$dirSubId"; - $this->db->query($sql); - - echo ""; - } - - # function to show featured directories - function showFeaturedSubmission($info="") { - $dirList = $this->getAllFeaturedDirectories(); - $this->set('list', $dirList); - /*if (empty($info['dir_id'])) { - $selDirInfo = $dirList[1]; - $selDirId = $selDirInfo['id']; - } else { - $selDirId = intval($info['dir_id']); - $selDirInfo = $dirList[$selDirId]; - } - $this->set('selDirId', $selDirId); - $this->set('selDirInfo', $selDirInfo);*/ + } + + # to unskip submission + function unSkipSubmission( $skipId ) { + + $skipId = intval($skipId); + $sql = "delete from skipdirectories where id=$skipId"; + $this->db->query($sql); + } + + # to get all skipped directories + function __getAllSkippedDir($websiteId){ + + $websiteId = intval($websiteId); + $dirList = array(); + $sql = "select directory_id from skipdirectories where website_id=$websiteId"; + $list = $this->db->select($sql); + if(count($list) > 0){ + foreach($list as $listInfo){ + $dirList[] = $listInfo['directory_id']; + } + } + + return $dirList; + } + + # func to show Skipped Directories + function showSkippedDirectories($searchInfo=''){ + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + $this->set('onChange', "scriptDoLoadPost('directories.php', 'search_form', 'content', '&sec=skipped')"); + + $conditions = empty ($websiteId) ? "" : " and ds.website_id=$websiteId"; + $pageScriptPath = 'directories.php?sec=skipped&website_id='.$websiteId; + $this->set('searchInfo', $searchInfo); + + // search for name + if (!empty($searchInfo['search_name'])) { + $conditions .= " and d.submit_url like '%".addslashes($searchInfo['search_name'])."%'"; + $pageScriptPath .= "&search_name=" . $searchInfo['search_name']; + } + + $sql = "select ds.* ,d.domain,d.pagerank, d.submit_url + from skipdirectories ds,directories d where ds.directory_id=d.id $conditions order by id desc,d.domain"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages($pageScriptPath, '', 'scriptDoLoad', 'content'); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + $reportList = $this->db->select($sql); + + $this->set('list', $reportList); + $this->set('pageNo', $_GET['pageno']); + $this->set('websiteId', $websiteId); + $this->render('directory/skippeddirs'); + } + + # func to show submision reports + function showSubmissionReports($searchInfo=''){ + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + $this->set('onChange', "scriptDoLoadPost('directories.php', 'search_form', 'content', '&sec=reports')"); + + $conditions = empty ($websiteId) ? "" : " and ds.website_id=$websiteId"; + $conditions .= empty ($searchInfo['active']) ? "" : " and ds.active=".($searchInfo['active']=='pending' ? 0 : 1); + + $pageScriptPath = 'directories.php?sec=reports&website_id='.$websiteId.'&active='.$searchInfo['active']; + $this->set('searchInfo', $searchInfo); + + // search for name + if (!empty($searchInfo['search_name'])) { + $conditions .= " and d.submit_url like '%".addslashes($searchInfo['search_name'])."%'"; + $pageScriptPath .= "&search_name=" . $searchInfo['search_name']; + } + + $sql = "select ds.* ,d.domain,d.pagerank, d.submit_url from dirsubmitinfo ds,directories d + where ds.directory_id=d.id $conditions order by submit_time desc,d.domain"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages($pageScriptPath, '', 'scriptDoLoad', 'content'); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + $reportList = $this->db->select($sql); + $this->set('pageScriptPath', $pageScriptPath); + $this->set('pageNo', $_GET['pageno']); + $this->set('activeVal', $searchInfo['active']); + $this->set('list', $reportList); + $this->render('directory/directoryreport'); + } + + function changeConfirmStatus($dirInfo){ + + $dirInfo['id'] = intval($dirInfo['id']); + $status = ($dirInfo['confirm']=='Yes') ? 0 : 1; + $sql = "Update dirsubmitinfo set status=$status where id=".$dirInfo['id']; + $this->db->query($sql); + } + + function showConfirmStatus($id){ + + $id = intval($id); + $sql = "select status from dirsubmitinfo where id=".$id; + $statusInfo = $this->db->select($sql, true); + + $confirm = empty($statusInfo['status']) ? "No" : "Yes"; + $confirmId = "confirm_".$id; + $confirmLink = "$confirm"; + + print $confirmLink; + } + + function checkSubmissionStatus($dirInfo){ + + $dirInfo['id'] = intval($dirInfo['id']); + $sql = "select ds.* ,d.domain,d.search_script,w.url + from dirsubmitinfo ds,directories d,websites w + where ds.directory_id=d.id and ds.website_id=w.id + and ds.id=". $dirInfo['id']; + $statusInfo = $this->db->select($sql, true); + + $searchUrl = (preg_match('/\/$/', $statusInfo['domain'])) ? $statusInfo['domain'].$statusInfo['search_script'] : $statusInfo['domain']."/".$statusInfo['search_script']; + $keyword = formatUrl($statusInfo['url']); + $searchUrl = str_replace('[--keyword--]', urlencode($keyword), $searchUrl); + + $ret = $this->spider->getContent($searchUrl); + if(empty($ret['error'])){ + if(stristr($ret['page'], 'href="'.$statusInfo['url'].'"')){ + return 1; + }elseif(stristr($ret['page'], "href='".$statusInfo['url']."'")){ + return 1; + }elseif(stristr($ret['page'], 'href='.$statusInfo['url'])){ + return 1; + } + } + return 0; + } + + function updateSubmissionStatus($dirId, $status){ + $status = intval($status); + $dirId = intval($dirId); + $sql = "Update dirsubmitinfo set active=$status where id=".$dirId; + $this->db->query($sql); + } + + function showSubmissionStatus($id){ + + $id = intval($id); + $sql = "select active from dirsubmitinfo where id=".$id; + $statusInfo = $this->db->select($sql, true); + + print empty($statusInfo['active']) ? $this->spTextDir["Pending"] : $this->spTextDir["Approved"]; + } + + function checkSubmissionReports( $searchInfo ) { + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $this->set('websiteList', $websiteController->__getAllWebsites($userId, true)); + $this->set('websiteNull', true); + $this->set('onClick', "scriptDoLoadPost('directories.php', 'search_form', 'subcontent', '&sec=checksub')"); + + $this->render('directory/checksubmission'); + } + + function generateSubmissionReports( $searchInfo ){ + + $searchInfo['website_id'] = intval($searchInfo['website_id']); + if(empty($searchInfo['website_id'])) { + echo ""; + return; + } + + $sql = "select ds.* ,d.domain + from dirsubmitinfo ds,directories d + where ds.directory_id=d.id + and ds.website_id={$searchInfo['website_id']} and ds.active=0 + order by submit_time"; + $reportList = $this->db->select($sql); + $this->set('list', $reportList); + $this->render('directory/generatesubmission'); + } + + function deleteSubmissionReports($dirSubId){ + + $dirSubId = intval($dirSubId); + $sql = "delete from dirsubmitinfo where id=$dirSubId"; + $this->db->query($sql); + + echo ""; + } + + # function to show featured directories + function showFeaturedSubmission($info="") { + $dirList = $this->getAllFeaturedDirectories(); + $this->set('list', $dirList); + /*if (empty($info['dir_id'])) { + $selDirInfo = $dirList[1]; + $selDirId = $selDirInfo['id']; + } else { + $selDirId = intval($info['dir_id']); + $selDirInfo = $dirList[$selDirId]; + } + $this->set('selDirId', $selDirId); + $this->set('selDirInfo', $selDirInfo);*/ $this->render('directory/featuredsubmission'); - } - - # function to get all features directories - function getAllFeaturedDirectories() { - $sql = "SELECT * FROM featured_directories where status=1 order by google_pagerank DESC"; - $list = $this->db->select($sql); - $dirList = array(); - foreach ($list as $listInfo) { - $dirList[$listInfo['id']] = $listInfo; - } - return $dirList; - } - - # func to get all directories - function getAllDirectories($searchInfo=array()) { - $sql = "SELECT * FROM directories "; - $i = 0; - foreach($searchInfo as $col => $value){ - $and = ($i++) ? "and" : "where"; - $sql .= " $and $col='$value'"; - } - $sql .= "order by id"; - $dirList = $this->db->select($sql); - - return $dirList; - } - - # func to get dir info - function getDirectoryInfo($dirId) { - - $dirId = intval($dirId); - $sql = "SELECT * FROM directories where id=$dirId"; - $dirInfo = $this->db->select($sql, true); - return $dirInfo; - } - - # func to show directory manager - function showDirectoryManager($info=''){ - $info = sanitizeData($info); - $info['stscheck'] = isset($info['stscheck']) ? intval($info['stscheck']) : 1; - $capcheck = isset($info['capcheck']) ? (($info['capcheck'] == 'yes') ? 1 : 0 ) : ""; - $sql = "SELECT *,l.lang_name FROM directories d,languages l where d.lang_code=l.lang_code and working='{$info['stscheck']}'"; - if(!empty($info['dir_name'])) $sql .= " and domain like '%".addslashes($info['dir_name'])."%'"; - if($info['capcheck'] != '') $sql .= " and is_captcha='$capcheck'"; - - // check for page rank - if(isset($info['pagerank']) && ($info['pagerank'] != '')) { - $prMax = intval($info['pagerank']) + 0.5; - $prMin = intval($info['pagerank']) - 0.5; - $sql .= " and pagerank<$prMax and pagerank>=$prMin"; - } - - if (!empty($info['langcode'])) { $info['lang_code'] = $info['langcode']; } - if(!empty($info['lang_code'])) $sql .= " and d.lang_code='".addslashes($info['lang_code'])."'"; - $sql .= " order by id"; - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pageScriptPath = 'directories.php?sec=directorymgr&dir_name='.urlencode($info['dir_name'])."&stscheck={$info['stscheck']}&capcheck=".$info['capcheck']; - $pageScriptPath .= "&pagerank=".$info['pagerank']."&langcode=".$info['lang_code']; - $pagingDiv = $this->paging->printPages($pageScriptPath); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - - $statusList = array( - $_SESSION['text']['common']['Active'] => 1, - $_SESSION['text']['common']['Inactive'] => 0, - ); - $captchaList = array( - $_SESSION['text']['common']['Yes'] => 'yes', - $_SESSION['text']['common']['No'] => 'no', - ); - - $langCtrler = New LanguageController(); - $langList = $langCtrler->__getAllLanguages(); - $this->set('langList', $langList); - - $this->set('statusList', $statusList); - $this->set('captchaList', $captchaList); - $dirList = $this->db->select($sql); - $this->set('list', $dirList); - $this->set('info', $info); - $this->set('ctrler', $this); - $this->render('directory/list'); - } - - # func to change status of directory - function changeStatusDirectory($dirId, $status, $printLink=false){ - - $status = intval($status); - $dirId = intval($dirId); - $sql = "update directories set working=$status where id=$dirId"; - $this->db->query($sql); - - if($printLink){ - echo $this->getStatusLink($dirId, $status); - } - } - - # func to show directory check interface - function showCheckDirectory() { - - $this->render('directory/showcheckdir'); - } - - # function to start directory check - function startDirectoryCheckStatus($info=''){ - - $searchInfo = array(); - if(isset($info['stscheck']) && ($info['stscheck'] != '')){ - $searchInfo = array( - 'working' => $info['stscheck'], - ); - } - - $dirList = $this->getAllDirectories($searchInfo); - - $this->set('dirList', $dirList); - $this->render('directory/dirstatusgenerator'); - } - - # func to check directories active or not - function checkDirectoryStatus($dirId, $nodebug=0) { - - $dirId = intval($dirId); - $dirInfo = $this->getDirectoryInfo($dirId); - $active = 0; - $captcha = 0; - $spider = new Spider(); - $ret = $spider->getContent(addHttpToUrl($dirInfo['submit_url'])); - $prUpdate = ''; - $searchUpdate = ''; - $extraValUpdate = ''; - - if(empty($ret['error']) && !empty($ret['page'])) { - $page = $ret['page']; - - $matches = $this->isCategoryExists($page, $dirInfo['category_col']); - $active = empty($matches[0]) ? 0 : 1; - - $captcha = stristr($page, $dirInfo['captcha_script']) ? 1 : 0; - - // to check search script - if (stristr($page, 'name="search"')) { - $searchUpdate = ",search_script='index.php?search=[--keyword--]'"; - } - - // to check the value of the LINK_TYPE if phpld directory - if (($dirInfo['script_type_id'] == 1) && preg_match('/name="LINK_TYPE" value="(\d)"/s', $page)) { - $subject = array('LINK_TYPE=reciprocal', 'LINK_TYPE=normal', 'LINK_TYPE=free'); - $replace = array('reciprocal=1&LINK_TYPE=1', 'LINK_TYPE=2', 'LINK_TYPE=3'); - $dirInfo['extra_val'] = str_replace($subject, $replace, $dirInfo['extra_val']); - $extraValUpdate = ",extra_val='{$dirInfo['extra_val']}'"; - } - - if ($this->checkPR) { - include_once(SP_CTRLPATH."/rank.ctrl.php"); - $rankCtrler = New RankController(); - $rankInfo = $rankCtrler->__getMozRank(array($dirInfo['domain'])); - $pagerank = !empty($rankInfo[0]) ? $rankInfo[0] : 0; - $prUpdate = ",pagerank=$pagerank"; - } - } - - $sql = "update directories set working=$active,is_captcha=$captcha,checked=1 $prUpdate $searchUpdate $extraValUpdate where id=$dirId"; - $this->db->query($sql); - - if($nodebug){ - $captchaLabel = $captcha ? $_SESSION['text']['common']['Yes'] : $_SESSION['text']['common']['No']; - ?> - - checkPR) { - ?> - - getStatusLink($dirId, $active); - }else{ - echo "
Saved status of directory {$dirInfo['domain']}.....
"; - } - } - - # func to get status link - function getStatusLink($dirId, $status){ - if($status){ - $statLabel = "Active"; - $statVal = 0; - }else{ - $statLabel = "Inactive"; - $statVal = 1; - } - if (SP_DEMO) { - $statusLink = scriptAJAXLinkHref('demo', "", "", $_SESSION['text']['common'][$statLabel]); - } else { - $statusLink = scriptAJAXLinkHref('directories.php', 'status_'.$dirId, "sec=dirstatus&dir_id=$dirId&status=$statVal", $_SESSION['text']['common'][$statLabel]); - } - - return $statusLink; - } - - # to get total directory submission info - function __getTotalSubmitInfo($websiteId, $activeCheck=false){ - $sql = "select count(*) count from dirsubmitinfo where website_id=$websiteId"; - if($activeCheck) $sql .= " and active=1"; - - $countInfo = $this->db->select($sql, true); - return empty($countInfo['count']) ? 0 : $countInfo['count']; - } - - # function to log submission data - function logSubmissionResult($content, $dirId, $websiteId) { - - $filename = SP_TMPPATH."/subres_web".$websiteId."_dir".$dirId.".html"; - $fp = fopen($filename, 'w'); - fwrite($fp, $content); - fclose($fp); - - } - - # function to get directory script type meta info - function getDirectoryScriptMetaInfo($id) { - $id = empty($id) ? 1 : $id; - $sql = "SELECT * FROM di_directory_meta where id=$id"; - $scriptInfo = $this->db->select($sql, true); - return $scriptInfo; - } -} + } + + # function to get all features directories + function getAllFeaturedDirectories() { + $sql = "SELECT * FROM featured_directories where status=1 order by google_pagerank DESC"; + $list = $this->db->select($sql); + $dirList = array(); + foreach ($list as $listInfo) { + $dirList[$listInfo['id']] = $listInfo; + } + return $dirList; + } + + # func to get all directories + function getAllDirectories($searchInfo=array()) { + $sql = "SELECT * FROM directories "; + $i = 0; + foreach($searchInfo as $col => $value){ + $and = ($i++) ? "and" : "where"; + $sql .= " $and $col='$value'"; + } + $sql .= "order by id"; + $dirList = $this->db->select($sql); + + return $dirList; + } + + # func to get dir info + function getDirectoryInfo($dirId) { + + $dirId = intval($dirId); + $sql = "SELECT * FROM directories where id=$dirId"; + $dirInfo = $this->db->select($sql, true); + return $dirInfo; + } + + # func to show directory manager + function showDirectoryManager($info=''){ + $info = sanitizeData($info); + $info['stscheck'] = isset($info['stscheck']) ? intval($info['stscheck']) : 1; + $capcheck = isset($info['capcheck']) ? (($info['capcheck'] == 'yes') ? 1 : 0 ) : ""; + $sql = "SELECT *,l.lang_name FROM directories d,languages l where d.lang_code=l.lang_code and working='{$info['stscheck']}'"; + if(!empty($info['dir_name'])) $sql .= " and domain like '%".addslashes($info['dir_name'])."%'"; + if($info['capcheck'] != '') $sql .= " and is_captcha='$capcheck'"; + + // check for page rank + if(isset($info['pagerank']) && ($info['pagerank'] != '')) { + $prMax = intval($info['pagerank']) + 0.5; + $prMin = intval($info['pagerank']) - 0.5; + $sql .= " and pagerank<$prMax and pagerank>=$prMin"; + } + + if (!empty($info['langcode'])) { $info['lang_code'] = $info['langcode']; } + if(!empty($info['lang_code'])) $sql .= " and d.lang_code='".addslashes($info['lang_code'])."'"; + $sql .= " order by id"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pageScriptPath = 'directories.php?sec=directorymgr&dir_name='.urlencode($info['dir_name'])."&stscheck={$info['stscheck']}&capcheck=".$info['capcheck']; + $pageScriptPath .= "&pagerank=".$info['pagerank']."&langcode=".$info['lang_code']; + $pagingDiv = $this->paging->printPages($pageScriptPath); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + $statusList = array( + $_SESSION['text']['common']['Active'] => 1, + $_SESSION['text']['common']['Inactive'] => 0, + ); + $captchaList = array( + $_SESSION['text']['common']['Yes'] => 'yes', + $_SESSION['text']['common']['No'] => 'no', + ); + + $langCtrler = New LanguageController(); + $langList = $langCtrler->__getAllLanguages(); + $this->set('langList', $langList); + + $this->set('statusList', $statusList); + $this->set('captchaList', $captchaList); + $dirList = $this->db->select($sql); + $this->set('list', $dirList); + $this->set('info', $info); + $this->set('ctrler', $this); + $this->render('directory/list'); + } + + # func to change status of directory + function changeStatusDirectory($dirId, $status, $printLink=false){ + + $status = intval($status); + $dirId = intval($dirId); + $sql = "update directories set working=$status where id=$dirId"; + $this->db->query($sql); + + if($printLink){ + echo $this->getStatusLink($dirId, $status); + } + } + + # func to show directory check interface + function showCheckDirectory() { + + $this->render('directory/showcheckdir'); + } + + # function to start directory check + function startDirectoryCheckStatus($info=''){ + + $searchInfo = array(); + if(isset($info['stscheck']) && ($info['stscheck'] != '')){ + $searchInfo = array( + 'working' => $info['stscheck'], + ); + } + + $dirList = $this->getAllDirectories($searchInfo); + + $this->set('dirList', $dirList); + $this->render('directory/dirstatusgenerator'); + } + + # func to check directories active or not + function checkDirectoryStatus($dirId, $nodebug=0) { + + $dirId = intval($dirId); + $dirInfo = $this->getDirectoryInfo($dirId); + $active = 0; + $captcha = 0; + $spider = new Spider(); + $ret = $spider->getContent(addHttpToUrl($dirInfo['submit_url'])); + $prUpdate = ''; + $searchUpdate = ''; + $extraValUpdate = ''; + + if(empty($ret['error']) && !empty($ret['page'])) { + $page = $ret['page']; + + $matches = $this->isCategoryExists($page, $dirInfo['category_col']); + $active = empty($matches[0]) ? 0 : 1; + + $captcha = stristr($page, $dirInfo['captcha_script']) ? 1 : 0; + + // to check search script + if (stristr($page, 'name="search"')) { + $searchUpdate = ",search_script='index.php?search=[--keyword--]'"; + } + + // to check the value of the LINK_TYPE if phpld directory + if (($dirInfo['script_type_id'] == 1) && preg_match('/name="LINK_TYPE" value="(\d)"/s', $page)) { + $subject = array('LINK_TYPE=reciprocal', 'LINK_TYPE=normal', 'LINK_TYPE=free'); + $replace = array('reciprocal=1&LINK_TYPE=1', 'LINK_TYPE=2', 'LINK_TYPE=3'); + $dirInfo['extra_val'] = str_replace($subject, $replace, $dirInfo['extra_val']); + $extraValUpdate = ",extra_val='{$dirInfo['extra_val']}'"; + } + + if ($this->checkPR) { + include_once(SP_CTRLPATH."/rank.ctrl.php"); + $rankCtrler = New RankController(); + $rankInfo = $rankCtrler->__getMozRank(array($dirInfo['domain'])); + $pagerank = !empty($rankInfo[0]) ? $rankInfo[0] : 0; + $prUpdate = ",pagerank=$pagerank"; + } + } + + $sql = "update directories set working=$active,is_captcha=$captcha,checked=1 $prUpdate $searchUpdate $extraValUpdate where id=$dirId"; + $this->db->query($sql); + + if($nodebug){ + $captchaLabel = $captcha ? $_SESSION['text']['common']['Yes'] : $_SESSION['text']['common']['No']; + ?> + + checkPR) { + ?> + + getStatusLink($dirId, $active); + }else{ + echo "Saved status of directory {$dirInfo['domain']}.....
"; + } + } + + # func to get status link + function getStatusLink($dirId, $status){ + if($status){ + $statLabel = "Active"; + $statVal = 0; + }else{ + $statLabel = "Inactive"; + $statVal = 1; + } + if (SP_DEMO) { + $statusLink = scriptAJAXLinkHref('demo', "", "", $_SESSION['text']['common'][$statLabel]); + } else { + $statusLink = scriptAJAXLinkHref('directories.php', 'status_'.$dirId, "sec=dirstatus&dir_id=$dirId&status=$statVal", $_SESSION['text']['common'][$statLabel]); + } + + return $statusLink; + } + + # to get total directory submission info + function __getTotalSubmitInfo($websiteId, $activeCheck=false){ + $sql = "select count(*) count from dirsubmitinfo where website_id=$websiteId"; + if($activeCheck) $sql .= " and active=1"; + + $countInfo = $this->db->select($sql, true); + return empty($countInfo['count']) ? 0 : $countInfo['count']; + } + + # function to log submission data + function logSubmissionResult($content, $dirId, $websiteId) { + + $filename = SP_TMPPATH."/subres_web".$websiteId."_dir".$dirId.".html"; + $fp = fopen($filename, 'w'); + fwrite($fp, $content); + fclose($fp); + + } + + # function to get directory script type meta info + function getDirectoryScriptMetaInfo($id) { + $id = empty($id) ? 1 : $id; + $sql = "SELECT * FROM di_directory_meta where id=$id"; + $scriptInfo = $this->db->select($sql, true); + return $scriptInfo; + } +} ?> \ No newline at end of file diff --git a/controllers/index.ctrl.php b/controllers/index.ctrl.php index a2f34b06..08ec8912 100644 --- a/controllers/index.ctrl.php +++ b/controllers/index.ctrl.php @@ -1,222 +1,222 @@ -getLanguageTexts('home', $_SESSION['lang_code']); - $this->set('spTextHome', $spTextHome); - if(isLoggedIn()){ - - /*checkLoggedIn(); - isHavingWebsite(); - $userId = isLoggedIn(); - $exportVersion = false; - switch($searchInfo['doc_type']){ - - case "export": - $exportVersion = true; - $exportContent = ""; - break; - - case "pdf": - $this->set('pdfVersion', true); - break; - - case "print": - $this->set('printVersion', true); - break; - } - - $sql = "select * from websites w where status=1"; - - // if admin user - if (isAdmin()) { - $userCtrler = New UserController(); - $userList = $userCtrler->__getAllUsersHavingWebsite(); - $this->set('userList', $userList); - $webUserId = isset($searchInfo['user_id']) ? intval($searchInfo['user_id']) : $userList[0]['id']; - - // if user id is passed - if (!empty($webUserId)) { - $sql .= " and user_id=$webUserId"; - } - - // if print method called - if ( ($searchInfo['doc_type'] == 'print') && !empty($webUserId)) { - $userInfo = $userCtrler->__getUserInfo($webUserId); - $this->set('userName', $userInfo['username']); - } - - } else { - $webUserId = $userId; - $sql = "select * from websites w where user_id=$webUserId"; - } - - $pageScriptPath = "index.php?user_id=$webUserId"; - $this->set('webUserId', $webUserId); - $info['pageno'] = intval($info['pageno']); - - // search for user name - if (!empty($searchInfo['search_name'])) { - $sql .= " and (w.name like '%".addslashes($searchInfo['search_name'])."%' - or w.url like '%".addslashes($searchInfo['search_name'])."%')"; - $pageScriptPath .= "&search_name=" . $searchInfo['search_name']; - } - - $sql .= " order by w.name"; - - // pagination setup - if (!in_array($searchInfo['doc_type'], array('export', 'pdf'))) { - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages($pageScriptPath, "", "link"); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - $this->set('pageNo', $info['pageno']); - } - - $list = $this->db->select($sql); - - include_once(SP_CTRLPATH."/saturationchecker.ctrl.php"); - include_once(SP_CTRLPATH."/rank.ctrl.php"); - include_once(SP_CTRLPATH."/backlink.ctrl.php"); - $rankCtrler = New RankController(); - $backlinlCtrler = New BacklinkController(); - $saturationCtrler = New SaturationCheckerController(); - $dirCtrler = New DirectoryController(); - - $fromTime = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); - $toTime = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - - $websiteList = array(); - foreach($list as $listInfo){ - - # rank reports - $report = $rankCtrler->__getWebsiteRankReport($listInfo['id'], $fromTime, $toTime); - $report = $report[0]; - $listInfo['alexarank'] = empty($report['alexa_rank']) ? "-" : $report['alexa_rank']." ".$report['rank_diff_alexa']; - $listInfo['mozrank'] = empty($report['moz_rank']) ? "-" : $report['moz_rank']." ".$report['rank_diff_moz']; - - # back links reports - $report = $backlinlCtrler->__getWebsitebacklinkReport($listInfo['id'], $fromTime, $toTime); - $report = $report[0]; - $listInfo['google']['backlinks'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google']; - $listInfo['alexa']['backlinks'] = empty($report['alexa']) ? "-" : $report['alexa']." ".$report['rank_diff_alexa']; - $listInfo['msn']['backlinks'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn']; - - # rank reports - $report = $saturationCtrler->__getWebsiteSaturationReport($listInfo['id'], $fromTime, $toTime); - $report = $report[0]; - $listInfo['google']['indexed'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google']; - $listInfo['msn']['indexed'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn']; - - $listInfo['dirsub']['total'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id']); - $listInfo['dirsub']['active'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id'], true); - $websiteList[] = $listInfo; - } - - // if export function called - if ($exportVersion) { - $exportContent .= createExportContent( array()); - $exportContent .= createExportContent( array()); - $exportContent .= createExportContent( array('', $spTextHome['Website Statistics'], '')); - - if ((isAdmin() && !empty($webUserId))) { - $exportContent .= createExportContent( array()); - $exportContent .= createExportContent( array()); - $userInfo = $userCtrler->__getUserInfo($webUserId); - $exportContent .= createExportContent( array($_SESSION['text']['common']['User'], $userInfo['username'])); - } - - $exportContent .= createExportContent( array()); - $headList = array( - $_SESSION['text']['common']['Id'], - $_SESSION['text']['common']['Website'], - $_SESSION['text']['common']['MOZ Rank'], - $_SESSION['text']['common']['Alexa Rank'], - 'Google '.$spTextHome['Backlinks'], - 'alexa '.$spTextHome['Backlinks'], - 'Bing '.$spTextHome['Backlinks'], - 'Google '.$spTextHome['Indexed'], - 'Bing '.$spTextHome['Indexed'], - $_SESSION['text']['common']['Total'].' Submission', - $_SESSION['text']['common']['Active'].' Submission', - ); - $exportContent .= createExportContent( $headList); - foreach ($websiteList as $websiteInfo) { - $valueList = array( - $websiteInfo['id'], - $websiteInfo['url'], - strip_tags($websiteInfo['mozrank']), - strip_tags($websiteInfo['alexarank']), - strip_tags($websiteInfo['google']['backlinks']), - strip_tags($websiteInfo['alexa']['backlinks']), - strip_tags($websiteInfo['msn']['backlinks']), - strip_tags($websiteInfo['google']['indexed']), - strip_tags($websiteInfo['msn']['indexed']), - $websiteInfo['dirsub']['total'], - $websiteInfo['dirsub']['active'], - ); - $exportContent .= createExportContent( $valueList); - } - exportToCsv('website_statistics', $exportContent); - } else { - - $this->set('websiteList', $websiteList); - - // if pdf export - if ($searchInfo['doc_type'] == "pdf") { - $fromTimeTxt = date('Y-m-d', $fromTime); - $toTimeTxt = date('Y-m-d', $toTime); - exportToPdf($this->getViewContent('user/userhome'), "account_summary_$fromTimeTxt-$toTimeTxt.pdf"); - } else { - $layout = ($searchInfo['doc_type'] == "print") ? "ajax" : ""; - $this->set('searchInfo', $searchInfo); - $this->render('user/userhome', $layout); - } - - }*/ - - $this->render('user/userhome'); - }else{ - $this->render('home'); - } - } - - # show login form - function showLoginForm(){ - $this->render('common/login'); - } - - # function to show support page - function showSupport() { - $this->set('spTextSupport', $this->getLanguageTexts('support', $_SESSION['lang_code'])); - $this->render('support'); - } - -} +getLanguageTexts('home', $_SESSION['lang_code']); + $this->set('spTextHome', $spTextHome); + if(isLoggedIn()){ + + /*checkLoggedIn(); + isHavingWebsite(); + $userId = isLoggedIn(); + $exportVersion = false; + switch($searchInfo['doc_type']){ + + case "export": + $exportVersion = true; + $exportContent = ""; + break; + + case "pdf": + $this->set('pdfVersion', true); + break; + + case "print": + $this->set('printVersion', true); + break; + } + + $sql = "select * from websites w where status=1"; + + // if admin user + if (isAdmin()) { + $userCtrler = New UserController(); + $userList = $userCtrler->__getAllUsersHavingWebsite(); + $this->set('userList', $userList); + $webUserId = isset($searchInfo['user_id']) ? intval($searchInfo['user_id']) : $userList[0]['id']; + + // if user id is passed + if (!empty($webUserId)) { + $sql .= " and user_id=$webUserId"; + } + + // if print method called + if ( ($searchInfo['doc_type'] == 'print') && !empty($webUserId)) { + $userInfo = $userCtrler->__getUserInfo($webUserId); + $this->set('userName', $userInfo['username']); + } + + } else { + $webUserId = $userId; + $sql = "select * from websites w where user_id=$webUserId"; + } + + $pageScriptPath = "index.php?user_id=$webUserId"; + $this->set('webUserId', $webUserId); + $info['pageno'] = intval($info['pageno']); + + // search for user name + if (!empty($searchInfo['search_name'])) { + $sql .= " and (w.name like '%".addslashes($searchInfo['search_name'])."%' + or w.url like '%".addslashes($searchInfo['search_name'])."%')"; + $pageScriptPath .= "&search_name=" . $searchInfo['search_name']; + } + + $sql .= " order by w.name"; + + // pagination setup + if (!in_array($searchInfo['doc_type'], array('export', 'pdf'))) { + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages($pageScriptPath, "", "link"); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + $this->set('pageNo', $info['pageno']); + } + + $list = $this->db->select($sql); + + include_once(SP_CTRLPATH."/saturationchecker.ctrl.php"); + include_once(SP_CTRLPATH."/rank.ctrl.php"); + include_once(SP_CTRLPATH."/backlink.ctrl.php"); + $rankCtrler = New RankController(); + $backlinlCtrler = New BacklinkController(); + $saturationCtrler = New SaturationCheckerController(); + $dirCtrler = New DirectoryController(); + + $fromTime = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); + $toTime = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + + $websiteList = array(); + foreach($list as $listInfo){ + + # rank reports + $report = $rankCtrler->__getWebsiteRankReport($listInfo['id'], $fromTime, $toTime); + $report = $report[0]; + $listInfo['alexarank'] = empty($report['alexa_rank']) ? "-" : $report['alexa_rank']." ".$report['rank_diff_alexa']; + $listInfo['mozrank'] = empty($report['moz_rank']) ? "-" : $report['moz_rank']." ".$report['rank_diff_moz']; + + # back links reports + $report = $backlinlCtrler->__getWebsitebacklinkReport($listInfo['id'], $fromTime, $toTime); + $report = $report[0]; + $listInfo['google']['backlinks'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google']; + $listInfo['alexa']['backlinks'] = empty($report['alexa']) ? "-" : $report['alexa']." ".$report['rank_diff_alexa']; + $listInfo['msn']['backlinks'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn']; + + # rank reports + $report = $saturationCtrler->__getWebsiteSaturationReport($listInfo['id'], $fromTime, $toTime); + $report = $report[0]; + $listInfo['google']['indexed'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google']; + $listInfo['msn']['indexed'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn']; + + $listInfo['dirsub']['total'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id']); + $listInfo['dirsub']['active'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id'], true); + $websiteList[] = $listInfo; + } + + // if export function called + if ($exportVersion) { + $exportContent .= createExportContent( array()); + $exportContent .= createExportContent( array()); + $exportContent .= createExportContent( array('', $spTextHome['Website Statistics'], '')); + + if ((isAdmin() && !empty($webUserId))) { + $exportContent .= createExportContent( array()); + $exportContent .= createExportContent( array()); + $userInfo = $userCtrler->__getUserInfo($webUserId); + $exportContent .= createExportContent( array($_SESSION['text']['common']['User'], $userInfo['username'])); + } + + $exportContent .= createExportContent( array()); + $headList = array( + $_SESSION['text']['common']['Id'], + $_SESSION['text']['common']['Website'], + $_SESSION['text']['common']['MOZ Rank'], + $_SESSION['text']['common']['Alexa Rank'], + 'Google '.$spTextHome['Backlinks'], + 'alexa '.$spTextHome['Backlinks'], + 'Bing '.$spTextHome['Backlinks'], + 'Google '.$spTextHome['Indexed'], + 'Bing '.$spTextHome['Indexed'], + $_SESSION['text']['common']['Total'].' Submission', + $_SESSION['text']['common']['Active'].' Submission', + ); + $exportContent .= createExportContent( $headList); + foreach ($websiteList as $websiteInfo) { + $valueList = array( + $websiteInfo['id'], + $websiteInfo['url'], + strip_tags($websiteInfo['mozrank']), + strip_tags($websiteInfo['alexarank']), + strip_tags($websiteInfo['google']['backlinks']), + strip_tags($websiteInfo['alexa']['backlinks']), + strip_tags($websiteInfo['msn']['backlinks']), + strip_tags($websiteInfo['google']['indexed']), + strip_tags($websiteInfo['msn']['indexed']), + $websiteInfo['dirsub']['total'], + $websiteInfo['dirsub']['active'], + ); + $exportContent .= createExportContent( $valueList); + } + exportToCsv('website_statistics', $exportContent); + } else { + + $this->set('websiteList', $websiteList); + + // if pdf export + if ($searchInfo['doc_type'] == "pdf") { + $fromTimeTxt = date('Y-m-d', $fromTime); + $toTimeTxt = date('Y-m-d', $toTime); + exportToPdf($this->getViewContent('user/userhome'), "account_summary_$fromTimeTxt-$toTimeTxt.pdf"); + } else { + $layout = ($searchInfo['doc_type'] == "print") ? "ajax" : ""; + $this->set('searchInfo', $searchInfo); + $this->render('user/userhome', $layout); + } + + }*/ + + $this->render('user/userhome'); + }else{ + $this->render('home'); + } + } + + # show login form + function showLoginForm(){ + $this->render('common/login'); + } + + # function to show support page + function showSupport() { + $this->set('spTextSupport', $this->getLanguageTexts('support', $_SESSION['lang_code'])); + $this->render('support'); + } + +} ?> \ No newline at end of file diff --git a/controllers/information.ctrl.php b/controllers/information.ctrl.php index 3b802640..ba443a03 100644 --- a/controllers/information.ctrl.php +++ b/controllers/information.ctrl.php @@ -1,118 +1,118 @@ -__getTodayInformation(); - - // if empty fetch directly from website - if (!isset($ret['page'])) { - - // get content directly from website - $ret = $this->spider->getContent(SP_NEWS_PAGE . "?lang=". $_SESSION['lang_code'], true, false); - - // update in db - $this->updateTodayInformation($ret['page']); - - } - - // check whether it contains required data - if (!empty($ret['page']) && stristr($ret['page'], "id='news_info'")) { - $this->set('newsContent', stripslashes($ret['page'])); - $this->render('common/topnewsbox', 'ajax'); - } - } - - } - - - /** - * function to get sponsors - */ - function getSponsors() { - - // get today's information - $ret = $this->__getTodayInformation('sponsors'); - - // if empty fetch directly from website - if (!isset($ret['page'])) { - - // get content directly from website - $ret = $this->spider->getContent(SP_SPONSOR_PAGE . "?lang=". $_SESSION['lang_code'], true, false); - - // update in db - $this->updateTodayInformation($ret['page'], 'sponsors'); - - } - - // check whether it contains required data - if (!empty($ret['page']) && stristr($ret['page'], 'class="contentmid"')) { - return $ret['page']; - } else { - return false; - } - - } - - /** - * function to update news in database - */ - function updateTodayInformation($content, $secName = 'news') { - - $todayDate = date('Y-m-d'); - $sql = "delete from information_list where info_type='" . addslashes($secName) . "'"; - $this->db->query($sql); - - $sql = "insert into information_list(info_type, content, update_date) - values('" . addslashes($secName) . "', '" . addslashes($content) . "', '{$todayDate}')"; - $this->db->query($sql); - - } - - /** - * function to get todays information - */ - function __getTodayInformation($secName = 'news') { - $sql = "select info_type, content as page from information_list where info_type='" . addslashes($secName) . "' - and update_date='" . date('Y-m-d') . "'"; - $info = $this->db->select($sql, true); - return $info; - } - -} +__getTodayInformation(); + + // if empty fetch directly from website + if (!isset($ret['page'])) { + + // get content directly from website + $ret = $this->spider->getContent(SP_NEWS_PAGE . "?lang=". $_SESSION['lang_code'], true, false); + + // update in db + $this->updateTodayInformation($ret['page']); + + } + + // check whether it contains required data + if (!empty($ret['page']) && stristr($ret['page'], "id='news_info'")) { + $this->set('newsContent', stripslashes($ret['page'])); + $this->render('common/topnewsbox', 'ajax'); + } + } + + } + + + /** + * function to get sponsors + */ + function getSponsors() { + + // get today's information + $ret = $this->__getTodayInformation('sponsors'); + + // if empty fetch directly from website + if (!isset($ret['page'])) { + + // get content directly from website + $ret = $this->spider->getContent(SP_SPONSOR_PAGE . "?lang=". $_SESSION['lang_code'], true, false); + + // update in db + $this->updateTodayInformation($ret['page'], 'sponsors'); + + } + + // check whether it contains required data + if (!empty($ret['page']) && stristr($ret['page'], 'class="contentmid"')) { + return $ret['page']; + } else { + return false; + } + + } + + /** + * function to update news in database + */ + function updateTodayInformation($content, $secName = 'news') { + + $todayDate = date('Y-m-d'); + $sql = "delete from information_list where info_type='" . addslashes($secName) . "'"; + $this->db->query($sql); + + $sql = "insert into information_list(info_type, content, update_date) + values('" . addslashes($secName) . "', '" . addslashes($content) . "', '{$todayDate}')"; + $this->db->query($sql); + + } + + /** + * function to get todays information + */ + function __getTodayInformation($secName = 'news') { + $sql = "select info_type, content as page from information_list where info_type='" . addslashes($secName) . "' + and update_date='" . date('Y-m-d') . "'"; + $info = $this->db->select($sql, true); + return $info; + } + +} ?> \ No newline at end of file diff --git a/controllers/keyword.ctrl.php b/controllers/keyword.ctrl.php index f5c4a822..f939dcac 100644 --- a/controllers/keyword.ctrl.php +++ b/controllers/keyword.ctrl.php @@ -1,455 +1,455 @@ -set('websiteList', $websiteController->__getAllWebsites($userId, true)); - $this->set('websiteId', $websiteId); - if ($websiteId) { - $conditions = " and k.website_id=$websiteId"; - $urlParams = "website_id=$websiteId"; - } else { - $conditions = ""; - } - - if (isset($info['status'])) { - if (($info['status']== 'active') || ($info['status']== 'inactive')) { - $statVal = ($info['status']=='active') ? 1 : 0; - $conditions .= " and k.status=$statVal"; - $urlParams .= "&status=".$info['status']; - } - } else { - $info['status'] = ''; - } - $this->set('statVal', $info['status']); - - if (empty($info['keyword'])) { - $info['keyword'] = ''; - } else { - $info['keyword'] = urldecode($info['keyword']); - $conditions .= " and k.name like '%".addslashes($info['keyword'])."%'"; - $urlParams .= "&keyword=".urlencode($info['keyword']); - } - $this->set('keyword', $info['keyword']); - - $sql = "select k.*,w.name website,w.status webstatus from keywords k,websites w where k.website_id=w.id and w.status=1"; - $sql .= isAdmin() ? "" : " and w.user_id=$userId"; - $sql .= " $conditions order by k.name"; - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages('keywords.php', '', 'scriptDoLoad', 'content', $urlParams); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - - # set keywords list - $keywordList = $this->db->select($sql); - $this->set('pageNo', $info['pageno']); - $langCtrler = New LanguageController(); - $countryCtrler = New CountryController(); - foreach ($keywordList as $i => $keyInfo) { - $info = $langCtrler->__getLanguageInfo($keyInfo['lang_code']); - $keywordList[$i]['lang_name'] = $info['lang_name']; - $info = $countryCtrler->__getCountryInfo($keyInfo['country_code']); - $keywordList[$i]['country_name'] = $info['country_name']; - } - $this->set('list', $keywordList); - $this->render('keyword/list'); - } - - # func to show keyword select box - function showKeywordSelectBox($userId='', $websiteId='', $keywordId=''){ - $this->set('keywordList', $this->__getAllKeywords($userId, $websiteId, true)); - $this->set('wkeywordId', $keywordId); - $this->render('keyword/keywordselectbox'); - } - - # func to change status - function __changeStatus($keywordId, $status){ - - $keywordId = intval($keywordId); - $sql = "update keywords set status=$status where id=$keywordId"; - $this->db->query($sql); - } - - # func to change status - function __deleteKeyword($keywordId){ - - $keywordId = intval($keywordId); - $sql = "delete from keywords where id=$keywordId"; - $this->db->query($sql); - - // delete related data - $sql = "delete sd.*, s.* from searchresults s, searchresultdetails sd where s.id=sd.searchresult_id and s.keyword_id=$keywordId"; - $this->db->query($sql); - } - - function newKeyword(){ - - $userId = isLoggedIn(); - - # Validate keyword count - if (!$this->validateKeywordCount($userId)) { - $this->set('validationMsg', $this->spTextKeyword['Your keyword count already reached the limit']); - } - - $websiteController = New WebsiteController(); - $this->set('websiteList', $websiteController->__getAllWebsites($userId, true)); - $langController = New LanguageController(); - $this->set('langList', $langController->__getAllLanguages()); - $this->set('langNull', true); - $countryController = New CountryController(); - $this->set('countryList', $countryController->__getAllCountries()); - $this->set('countryNull', true); - $seController = New SearchEngineController(); - $this->set('seList', $seController->__getAllSearchEngines()); - $this->render('keyword/new'); - } - - # create new keyword function - function createKeyword($listInfo, $apiCall = false){ - - $userId = isLoggedIn(); - $this->set('post', $listInfo); - $errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name'])); - $errMsg['website_id'] = formatErrorMsg($this->validate->checkBlank($listInfo['website_id'])); - if (!is_array($listInfo['searchengines'])) $listInfo['searchengines'] = array(); - $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); - $statusVal = isset($listInfo['status']) ? intval($listInfo['status']) : 1; - $seStr = is_array($listInfo['searchengines']) ? implode(':', $listInfo['searchengines']) : $listInfo['searchengines']; - - // verify the limit count for the user - if (!$this->validate->flagErr) { - - // Get the website user id, if admin is logged in - if (isAdmin() || $apiCall) { - $websiteCtrler = new WebsiteController(); - $websiteInfo = $websiteCtrler->__getWebsiteInfo($listInfo['website_id']); - $webUserId = $websiteInfo['user_id']; - } else { - $webUserId = $userId; - } - - // Validate keyword count - if (! $this->validateKeywordCount($webUserId)) { - $validationMsg = $this->spTextKeyword['Your keyword count already reached the limit']; - $this->set('validationMsg', $validationMsg); - $errMsg['limit_error'] = $validationMsg; - $this->validate->flagErr = true; - } - } - - // verify the form elements - if(!$this->validate->flagErr){ - $keyword = addslashes(trim($listInfo['name'])); - if (!$this->__checkName($keyword, $listInfo['website_id'])) { - $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); - $sql = "insert into keywords(name,lang_code,country_code,website_id,searchengines,status) - values('$keyword', '".addslashes($listInfo['lang_code'])."', '".addslashes($listInfo['country_code'])."', - ".intval($listInfo['website_id']).", '".addslashes($seStr)."', $statusVal)"; - $this->db->query($sql); - - // if api call - if ($apiCall) { - return array('success', 'Successfully created keyword'); - } else { - $this->listKeywords(); - exit; - } - - }else{ - $errMsg['name'] = formatErrorMsg($this->spTextKeyword['Keyword already exist']); - } - } - - // if api call - if ($apiCall) { - return array('error', $errMsg); - } else { - $this->set('errMsg', $errMsg); - $this->newKeyword(); - } - - } - - # function to import keywords - function importKeywords(){ - - $userId = isLoggedIn(); - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - - if (empty($_POST['website_id'])) { - $listInfo['website_id'] = $websiteList[0]['id']; - $this->set('post', $listInfo); - } - - $langController = New LanguageController(); - $this->set('langList', $langController->__getAllLanguages()); - $this->set('langNull', true); - - $countryController = New CountryController(); - $this->set('countryList', $countryController->__getAllCountries()); - $this->set('countryNull', true); - - $seController = New SearchEngineController(); - $this->set('seList', $seController->__getAllSearchEngines()); - - // Check the user website count for validation - if (!isAdmin()) { - $this->setValidationMessageForLimit($userId); - } - - $this->render('keyword/importkeywords'); - } - - # function to set validation message for the limit - function setValidationMessageForLimit($userId) { - - // Check the user website count for validation - $userTypeCtrlr = new UserTypeController(); - $userKeywordCount = count($this->__getAllKeywords($userId)); - $userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId); - $validCount = $userTypeDetails['keywordcount'] - $userKeywordCount; - $validCount = $validCount > 0 ? $validCount : 0; - $validationMsg = str_replace("[keywordcount]", "$validCount", $this->spTextKeyword['You can add only keywordcount keywords more']); - $this->set('validationMsg', $validationMsg); - - } - - # function to import keywords to the seo panel - function createImportedKeywords($listInfo){ - - $userId = isLoggedIn(); - $this->set('post', $listInfo); - $errMsg['keywords'] = formatErrorMsg($this->validate->checkBlank($listInfo['keywords'])); - if (!is_array($listInfo['searchengines'])) $listInfo['searchengines'] = array(); - $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); - - if(!$this->validate->flagErr){ - - $listInfo['website_id'] = intval($listInfo['website_id']); - $keywords = explode(",", $listInfo['keywords']); - $keyExist = false; - $keywordList = array(); - foreach ($keywords as $i => $keyword) { - $keyword = addslashes(trim($keyword)); - if ($this->__checkName($keyword, $listInfo['website_id'])) { - $errMsg['keywords'] = formatErrorMsg($_SESSION['text']['common']['Keyword']." '$keyword' ". $_SESSION['text']['label']['already exist']); - $keyExist = true; - break; - } - - // if keyword is not empty - if (!empty($keyword)) { - $keywordList[$i] = $keyword; - } - } - - // Check the user website count for validation - if (isAdmin()) { - $websiteCtrler = new WebsiteController(); - $websiteInfo = $websiteCtrler->__getWebsiteInfo($listInfo['website_id']); - $webUserId = $websiteInfo['user_id']; - } else { - $webUserId = $userId; - } - - // check whether keyword count exeeds the limit - if (!$this->validateKeywordCount($webUserId, count($keywordList))) { - $this->setValidationMessageForLimit($webUserId); - $keyExist = true; - } - - // if no error exists save keyword - if (!$keyExist) { - $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); - foreach ($keywordList as $keyword) { - $sql = "insert into keywords(name,lang_code,country_code,website_id,searchengines,status) - values('$keyword','".addslashes($listInfo['lang_code'])."','".addslashes($listInfo['country_code'])."', - ".intval($listInfo['website_id']).",'".implode(':', $listInfo['searchengines'])."',1)"; - $this->db->query($sql); - } - - $this->listKeywords($listInfo); - exit; - } - - } - $this->set('errMsg', $errMsg); - $this->importKeywords(); - } - - function __checkName($name, $websiteId){ - - $sql = "select id from keywords where name='$name' and website_id=$websiteId"; - $listInfo = $this->db->select($sql, true); - return empty($listInfo['id']) ? false : $listInfo['id']; - } - - # func to get all keywords - function __getAllKeywords($userId='', $websiteId='', $isAdminCheck=false, $orderByWeb=false, $orderByValue='ASC', $searchName = ''){ - $sql = "select k.*,w.name website,w.url weburl from keywords k,websites w where k.website_id=w.id and k.status=1"; - if(!$isAdminCheck || !isAdmin() ){ - if(!empty($userId)) $sql .= " and w.user_id=$userId"; - } - - if(!empty($websiteId)) $sql .= " and k.website_id=$websiteId"; - - if (!empty($searchName)) { - $sql .= " and k.name like '%".addslashes($searchName)."%'"; - } - - $sql .= $orderByWeb ? " order by w.id, k.name $orderByValue" : " order by k.name $orderByValue"; - $keywordList = $this->db->select($sql); - return $keywordList; - } - - function __getKeywordInfo($keywordId){ - - $keywordId = intval($keywordId); - $sql = "select * from keywords where id=$keywordId"; - $listInfo = $this->db->select($sql, true); - return empty($listInfo['id']) ? false : $listInfo; - } - - function editKeyword($keywordId, $listInfo=''){ - - $userId = isLoggedIn(); - $websiteController = New WebsiteController(); - $this->set('websiteList', $websiteController->__getAllWebsites($userId, true)); - $langController = New LanguageController(); - $this->set('langList', $langController->__getAllLanguages()); - $this->set('langNull', true); - $countryController = New CountryController(); - $this->set('countryList', $countryController->__getAllCountries()); - $this->set('countryNull', true); - $seController = New SearchEngineController(); - $this->set('seList', $seController->__getAllSearchEngines()); - if(!empty($keywordId)){ - if(empty($listInfo)){ - $listInfo = $this->__getKeywordInfo($keywordId); - $listInfo['oldName'] = $listInfo['name']; - $listInfo['searchengines'] = explode(':', $listInfo['searchengines']); - } - $this->set('post', $listInfo); - $this->render('keyword/edit'); - exit; - } - $this->listKeywords(); - } - - function updateKeyword($listInfo, $apiCall = false){ - $userId = isLoggedIn(); - $this->set('post', $listInfo); - $errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name'])); - $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); - $seStr = is_array($listInfo['searchengines']) ? implode(':', $listInfo['searchengines']) : $listInfo['searchengines']; - $statusVal = isset($listInfo['status']) ? "status = " . intval($listInfo['status']) ."," : ""; - - //validate form - if(!$this->validate->flagErr){ - - $listInfo['website_id'] = intval($listInfo['website_id']); - $listInfo['id'] = intval($listInfo['id']); - $keyword = addslashes(trim($listInfo['name'])); - if($listInfo['name'] != $listInfo['oldName']){ - if ($this->__checkName($keyword, $listInfo['website_id'])) { - $errMsg['name'] = formatErrorMsg($this->spTextKeyword['Keyword already exist']); - $this->validate->flagErr = true; - } - } - - if (!$this->validate->flagErr) { - $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); - $sql = "update keywords set - name = '$keyword', - lang_code = '".addslashes($listInfo['lang_code'])."', - country_code = '".addslashes($listInfo['country_code'])."', - website_id = {$listInfo['website_id']}, - $statusVal - searchengines = '".addslashes($seStr)."' - where id={$listInfo['id']}"; - $this->db->query($sql); - - // if api call - if ($apiCall) { - return array('success', 'Successfully updated keyword'); - } else { - $this->listKeywords(); - exit; - } - - } - } - - // if api call - if ($apiCall) { - return array('error', $errMsg); - } else { - $this->set('errMsg', $errMsg); - $this->editKeyword($listInfo['id'], $listInfo); - } - } - - function showKeywordReports($keywordId) { - $keywordId = intval($keywordId); - $this->checkUserIsObjectOwner($keywordId, 'keyword'); - echo ""; - } - - // Function to check / validate the user type keuword count - function validateKeywordCount($userId, $newCount = 1) { - $userCtrler = new UserController(); - - // if admin user id return true - if ($userCtrler->isAdminUserId($userId)) { - return true; - } - - $userTypeCtrlr = new UserTypeController(); - $userKeywordCount = count($this->__getAllKeywords($userId)); - $userKeywordCount += $newCount; - $userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId); - - // check whether count greater than limit - if ($userKeywordCount <= $userTypeDetails['keywordcount']) { - return true; - } else { - return false; - } - } - -} +set('websiteList', $websiteController->__getAllWebsites($userId, true)); + $this->set('websiteId', $websiteId); + if ($websiteId) { + $conditions = " and k.website_id=$websiteId"; + $urlParams = "website_id=$websiteId"; + } else { + $conditions = ""; + } + + if (isset($info['status'])) { + if (($info['status']== 'active') || ($info['status']== 'inactive')) { + $statVal = ($info['status']=='active') ? 1 : 0; + $conditions .= " and k.status=$statVal"; + $urlParams .= "&status=".$info['status']; + } + } else { + $info['status'] = ''; + } + $this->set('statVal', $info['status']); + + if (empty($info['keyword'])) { + $info['keyword'] = ''; + } else { + $info['keyword'] = urldecode($info['keyword']); + $conditions .= " and k.name like '%".addslashes($info['keyword'])."%'"; + $urlParams .= "&keyword=".urlencode($info['keyword']); + } + $this->set('keyword', $info['keyword']); + + $sql = "select k.*,w.name website,w.status webstatus from keywords k,websites w where k.website_id=w.id and w.status=1"; + $sql .= isAdmin() ? "" : " and w.user_id=$userId"; + $sql .= " $conditions order by k.name"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages('keywords.php', '', 'scriptDoLoad', 'content', $urlParams); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + # set keywords list + $keywordList = $this->db->select($sql); + $this->set('pageNo', $info['pageno']); + $langCtrler = New LanguageController(); + $countryCtrler = New CountryController(); + foreach ($keywordList as $i => $keyInfo) { + $info = $langCtrler->__getLanguageInfo($keyInfo['lang_code']); + $keywordList[$i]['lang_name'] = $info['lang_name']; + $info = $countryCtrler->__getCountryInfo($keyInfo['country_code']); + $keywordList[$i]['country_name'] = $info['country_name']; + } + $this->set('list', $keywordList); + $this->render('keyword/list'); + } + + # func to show keyword select box + function showKeywordSelectBox($userId='', $websiteId='', $keywordId=''){ + $this->set('keywordList', $this->__getAllKeywords($userId, $websiteId, true)); + $this->set('wkeywordId', $keywordId); + $this->render('keyword/keywordselectbox'); + } + + # func to change status + function __changeStatus($keywordId, $status){ + + $keywordId = intval($keywordId); + $sql = "update keywords set status=$status where id=$keywordId"; + $this->db->query($sql); + } + + # func to change status + function __deleteKeyword($keywordId){ + + $keywordId = intval($keywordId); + $sql = "delete from keywords where id=$keywordId"; + $this->db->query($sql); + + // delete related data + $sql = "delete sd.*, s.* from searchresults s, searchresultdetails sd where s.id=sd.searchresult_id and s.keyword_id=$keywordId"; + $this->db->query($sql); + } + + function newKeyword(){ + + $userId = isLoggedIn(); + + # Validate keyword count + if (!$this->validateKeywordCount($userId)) { + $this->set('validationMsg', $this->spTextKeyword['Your keyword count already reached the limit']); + } + + $websiteController = New WebsiteController(); + $this->set('websiteList', $websiteController->__getAllWebsites($userId, true)); + $langController = New LanguageController(); + $this->set('langList', $langController->__getAllLanguages()); + $this->set('langNull', true); + $countryController = New CountryController(); + $this->set('countryList', $countryController->__getAllCountries()); + $this->set('countryNull', true); + $seController = New SearchEngineController(); + $this->set('seList', $seController->__getAllSearchEngines()); + $this->render('keyword/new'); + } + + # create new keyword function + function createKeyword($listInfo, $apiCall = false){ + + $userId = isLoggedIn(); + $this->set('post', $listInfo); + $errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name'])); + $errMsg['website_id'] = formatErrorMsg($this->validate->checkBlank($listInfo['website_id'])); + if (!is_array($listInfo['searchengines'])) $listInfo['searchengines'] = array(); + $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); + $statusVal = isset($listInfo['status']) ? intval($listInfo['status']) : 1; + $seStr = is_array($listInfo['searchengines']) ? implode(':', $listInfo['searchengines']) : $listInfo['searchengines']; + + // verify the limit count for the user + if (!$this->validate->flagErr) { + + // Get the website user id, if admin is logged in + if (isAdmin() || $apiCall) { + $websiteCtrler = new WebsiteController(); + $websiteInfo = $websiteCtrler->__getWebsiteInfo($listInfo['website_id']); + $webUserId = $websiteInfo['user_id']; + } else { + $webUserId = $userId; + } + + // Validate keyword count + if (! $this->validateKeywordCount($webUserId)) { + $validationMsg = $this->spTextKeyword['Your keyword count already reached the limit']; + $this->set('validationMsg', $validationMsg); + $errMsg['limit_error'] = $validationMsg; + $this->validate->flagErr = true; + } + } + + // verify the form elements + if(!$this->validate->flagErr){ + $keyword = addslashes(trim($listInfo['name'])); + if (!$this->__checkName($keyword, $listInfo['website_id'])) { + $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); + $sql = "insert into keywords(name,lang_code,country_code,website_id,searchengines,status) + values('$keyword', '".addslashes($listInfo['lang_code'])."', '".addslashes($listInfo['country_code'])."', + ".intval($listInfo['website_id']).", '".addslashes($seStr)."', $statusVal)"; + $this->db->query($sql); + + // if api call + if ($apiCall) { + return array('success', 'Successfully created keyword'); + } else { + $this->listKeywords(); + exit; + } + + }else{ + $errMsg['name'] = formatErrorMsg($this->spTextKeyword['Keyword already exist']); + } + } + + // if api call + if ($apiCall) { + return array('error', $errMsg); + } else { + $this->set('errMsg', $errMsg); + $this->newKeyword(); + } + + } + + # function to import keywords + function importKeywords(){ + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + + if (empty($_POST['website_id'])) { + $listInfo['website_id'] = $websiteList[0]['id']; + $this->set('post', $listInfo); + } + + $langController = New LanguageController(); + $this->set('langList', $langController->__getAllLanguages()); + $this->set('langNull', true); + + $countryController = New CountryController(); + $this->set('countryList', $countryController->__getAllCountries()); + $this->set('countryNull', true); + + $seController = New SearchEngineController(); + $this->set('seList', $seController->__getAllSearchEngines()); + + // Check the user website count for validation + if (!isAdmin()) { + $this->setValidationMessageForLimit($userId); + } + + $this->render('keyword/importkeywords'); + } + + # function to set validation message for the limit + function setValidationMessageForLimit($userId) { + + // Check the user website count for validation + $userTypeCtrlr = new UserTypeController(); + $userKeywordCount = count($this->__getAllKeywords($userId)); + $userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId); + $validCount = $userTypeDetails['keywordcount'] - $userKeywordCount; + $validCount = $validCount > 0 ? $validCount : 0; + $validationMsg = str_replace("[keywordcount]", "$validCount", $this->spTextKeyword['You can add only keywordcount keywords more']); + $this->set('validationMsg', $validationMsg); + + } + + # function to import keywords to the seo panel + function createImportedKeywords($listInfo){ + + $userId = isLoggedIn(); + $this->set('post', $listInfo); + $errMsg['keywords'] = formatErrorMsg($this->validate->checkBlank($listInfo['keywords'])); + if (!is_array($listInfo['searchengines'])) $listInfo['searchengines'] = array(); + $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); + + if(!$this->validate->flagErr){ + + $listInfo['website_id'] = intval($listInfo['website_id']); + $keywords = explode(",", $listInfo['keywords']); + $keyExist = false; + $keywordList = array(); + foreach ($keywords as $i => $keyword) { + $keyword = addslashes(trim($keyword)); + if ($this->__checkName($keyword, $listInfo['website_id'])) { + $errMsg['keywords'] = formatErrorMsg($_SESSION['text']['common']['Keyword']." '$keyword' ". $_SESSION['text']['label']['already exist']); + $keyExist = true; + break; + } + + // if keyword is not empty + if (!empty($keyword)) { + $keywordList[$i] = $keyword; + } + } + + // Check the user website count for validation + if (isAdmin()) { + $websiteCtrler = new WebsiteController(); + $websiteInfo = $websiteCtrler->__getWebsiteInfo($listInfo['website_id']); + $webUserId = $websiteInfo['user_id']; + } else { + $webUserId = $userId; + } + + // check whether keyword count exeeds the limit + if (!$this->validateKeywordCount($webUserId, count($keywordList))) { + $this->setValidationMessageForLimit($webUserId); + $keyExist = true; + } + + // if no error exists save keyword + if (!$keyExist) { + $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); + foreach ($keywordList as $keyword) { + $sql = "insert into keywords(name,lang_code,country_code,website_id,searchengines,status) + values('$keyword','".addslashes($listInfo['lang_code'])."','".addslashes($listInfo['country_code'])."', + ".intval($listInfo['website_id']).",'".implode(':', $listInfo['searchengines'])."',1)"; + $this->db->query($sql); + } + + $this->listKeywords($listInfo); + exit; + } + + } + $this->set('errMsg', $errMsg); + $this->importKeywords(); + } + + function __checkName($name, $websiteId){ + + $sql = "select id from keywords where name='$name' and website_id=$websiteId"; + $listInfo = $this->db->select($sql, true); + return empty($listInfo['id']) ? false : $listInfo['id']; + } + + # func to get all keywords + function __getAllKeywords($userId='', $websiteId='', $isAdminCheck=false, $orderByWeb=false, $orderByValue='ASC', $searchName = ''){ + $sql = "select k.*,w.name website,w.url weburl from keywords k,websites w where k.website_id=w.id and k.status=1"; + if(!$isAdminCheck || !isAdmin() ){ + if(!empty($userId)) $sql .= " and w.user_id=$userId"; + } + + if(!empty($websiteId)) $sql .= " and k.website_id=$websiteId"; + + if (!empty($searchName)) { + $sql .= " and k.name like '%".addslashes($searchName)."%'"; + } + + $sql .= $orderByWeb ? " order by w.id, k.name $orderByValue" : " order by k.name $orderByValue"; + $keywordList = $this->db->select($sql); + return $keywordList; + } + + function __getKeywordInfo($keywordId){ + + $keywordId = intval($keywordId); + $sql = "select * from keywords where id=$keywordId"; + $listInfo = $this->db->select($sql, true); + return empty($listInfo['id']) ? false : $listInfo; + } + + function editKeyword($keywordId, $listInfo=''){ + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $this->set('websiteList', $websiteController->__getAllWebsites($userId, true)); + $langController = New LanguageController(); + $this->set('langList', $langController->__getAllLanguages()); + $this->set('langNull', true); + $countryController = New CountryController(); + $this->set('countryList', $countryController->__getAllCountries()); + $this->set('countryNull', true); + $seController = New SearchEngineController(); + $this->set('seList', $seController->__getAllSearchEngines()); + if(!empty($keywordId)){ + if(empty($listInfo)){ + $listInfo = $this->__getKeywordInfo($keywordId); + $listInfo['oldName'] = $listInfo['name']; + $listInfo['searchengines'] = explode(':', $listInfo['searchengines']); + } + $this->set('post', $listInfo); + $this->render('keyword/edit'); + exit; + } + $this->listKeywords(); + } + + function updateKeyword($listInfo, $apiCall = false){ + $userId = isLoggedIn(); + $this->set('post', $listInfo); + $errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name'])); + $errMsg['searchengines'] = formatErrorMsg($this->validate->checkBlank(implode('', $listInfo['searchengines']))); + $seStr = is_array($listInfo['searchengines']) ? implode(':', $listInfo['searchengines']) : $listInfo['searchengines']; + $statusVal = isset($listInfo['status']) ? "status = " . intval($listInfo['status']) ."," : ""; + + //validate form + if(!$this->validate->flagErr){ + + $listInfo['website_id'] = intval($listInfo['website_id']); + $listInfo['id'] = intval($listInfo['id']); + $keyword = addslashes(trim($listInfo['name'])); + if($listInfo['name'] != $listInfo['oldName']){ + if ($this->__checkName($keyword, $listInfo['website_id'])) { + $errMsg['name'] = formatErrorMsg($this->spTextKeyword['Keyword already exist']); + $this->validate->flagErr = true; + } + } + + if (!$this->validate->flagErr) { + $listInfo['searchengines'] = is_array($listInfo['searchengines']) ? $listInfo['searchengines'] : array(); + $sql = "update keywords set + name = '$keyword', + lang_code = '".addslashes($listInfo['lang_code'])."', + country_code = '".addslashes($listInfo['country_code'])."', + website_id = {$listInfo['website_id']}, + $statusVal + searchengines = '".addslashes($seStr)."' + where id={$listInfo['id']}"; + $this->db->query($sql); + + // if api call + if ($apiCall) { + return array('success', 'Successfully updated keyword'); + } else { + $this->listKeywords(); + exit; + } + + } + } + + // if api call + if ($apiCall) { + return array('error', $errMsg); + } else { + $this->set('errMsg', $errMsg); + $this->editKeyword($listInfo['id'], $listInfo); + } + } + + function showKeywordReports($keywordId) { + $keywordId = intval($keywordId); + $this->checkUserIsObjectOwner($keywordId, 'keyword'); + echo ""; + } + + // Function to check / validate the user type keuword count + function validateKeywordCount($userId, $newCount = 1) { + $userCtrler = new UserController(); + + // if admin user id return true + if ($userCtrler->isAdminUserId($userId)) { + return true; + } + + $userTypeCtrlr = new UserTypeController(); + $userKeywordCount = count($this->__getAllKeywords($userId)); + $userKeywordCount += $newCount; + $userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId); + + // check whether count greater than limit + if ($userKeywordCount <= $userTypeDetails['keywordcount']) { + return true; + } else { + return false; + } + } + +} ?> \ No newline at end of file diff --git a/controllers/language.ctrl.php b/controllers/language.ctrl.php index 5ae0f457..30814138 100644 --- a/controllers/language.ctrl.php +++ b/controllers/language.ctrl.php @@ -1,53 +1,53 @@ -db->select($sql); - return $langList; - } - - # fun to create resdirect url - function getRedirectUrl() { - $currUrl = getCurrentUrl(); - if (!stristr($currUrl, '?')) { - $currUrl .= "?"; - } - - $currUrl = preg_replace('/&lang_code=\w{2}$|&lang_code=\w{2}&/i', '', $currUrl, 1, $count); - return $currUrl; - } - - # func to get language info - function __getLanguageInfo($langCode) { - $sql = "select * from languages where lang_code='$langCode'"; - $langInfo = $this->db->select($sql, true); - return $langInfo; - } -} +db->select($sql); + return $langList; + } + + # fun to create resdirect url + function getRedirectUrl() { + $currUrl = getCurrentUrl(); + if (!stristr($currUrl, '?')) { + $currUrl .= "?"; + } + + $currUrl = preg_replace('/&lang_code=\w{2}$|&lang_code=\w{2}&/i', '', $currUrl, 1, $count); + return $currUrl; + } + + # func to get language info + function __getLanguageInfo($langCode) { + $sql = "select * from languages where lang_code='$langCode'"; + $langInfo = $this->db->select($sql, true); + return $langInfo; + } +} ?> \ No newline at end of file diff --git a/controllers/rank.ctrl.php b/controllers/rank.ctrl.php index 1c1a941f..eacddbe9 100644 --- a/controllers/rank.ctrl.php +++ b/controllers/rank.ctrl.php @@ -1,496 +1,496 @@ -render('rank/showquickrank'); - } - - function findQuickRank($searchInfo) { - $urlList = explode("\n", $searchInfo['website_urls']); - $list = array(); - $i = 1; - foreach ($urlList as $url) { - $url = sanitizeData($url); - if(!preg_match('/\w+/', $url)) continue; - if (SP_DEMO) { - if ($i++ > 10) break; - } - - $url = addHttpToUrl($url); - $list[] = str_replace(array("\n", "\r", "\r\n", "\n\r"), "", trim($url)); - } - - $mozRankList = $this->__getMozRank($list); - $this->set('mozRankList', $mozRankList); - - $this->set('list', $list); - $this->render('rank/findquickrank'); - } - - function printGooglePageRank($url){ - $pageRank = $this->__getGooglePageRank($url); - if($pageRank >= 0){ - $imageUrl = SP_IMGPATH."/pr/pr".$pageRank.".gif"; - }else{ - $imageUrl = SP_IMGPATH."/pr/pr.gif"; - } - - print "".$_SESSION['text']['common']['nowebsites']."!
"; - exit; - } - - $urlList = array(); - foreach ($websiteList as $websiteInfo) { - $urlList[] = addHttpToUrl($websiteInfo['url']); - } - - // get moz ranks - $mozRankList = $this->__getMozRank($urlList); - - // loop through each websites - foreach ( $websiteList as $i => $websiteInfo ) { - $websiteUrl = addHttpToUrl($websiteInfo['url']); - $websiteInfo['alexaRank'] = $this->__getAlexaRank($websiteUrl); - $websiteInfo['moz_rank'] = !empty($mozRankList[$i]) ? $mozRankList[$i] : 0; - - $this->saveRankResults($websiteInfo, true); - echo "".$this->spTextRank['Saved rank results of']." $websiteUrl.....
"; - } - } - - # function to save rank details - function saveRankResults($matchInfo, $remove=false) { - $time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - - if($remove){ - $sql = "delete from rankresults where website_id={$matchInfo['id']} and result_time=$time"; - $this->db->query($sql); - } - - $sql = "insert into rankresults(website_id,moz_rank,alexa_rank,result_time) - values({$matchInfo['id']},{$matchInfo['moz_rank']},{$matchInfo['alexaRank']},$time)"; - $this->db->query($sql); - } - - # function check whether reports already saved - function isReportsExists($websiteId, $time) { - $sql = "select website_id from rankresults where website_id=$websiteId and result_time=$time"; - $info = $this->db->select($sql, true); - return empty($info['website_id']) ? false : true; - } - - # func to show reports - function showReports($searchInfo = '') { - - $userId = isLoggedIn(); - if (!empty ($searchInfo['from_time'])) { - $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); - } else { - $fromTime = mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); - } - if (!empty ($searchInfo['to_time'])) { - $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); - } else { - $toTime = @mktime(); - } - $this->set('fromTime', date('Y-m-d', $fromTime)); - $this->set('toTime', date('Y-m-d', $toTime)); - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); - $this->set('websiteId', $websiteId); - - $conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId"; - $sql = "select s.* ,w.name - from rankresults s,websites w - where s.website_id=w.id - and result_time>= $fromTime and result_time<=$toTime $conditions - order by result_time"; - $reportList = $this->db->select($sql); - - $i = 0; - $colList = array('moz' => 'moz_rank', 'alexa' => 'alexa_rank'); - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = 0; - } - - # loop throgh rank - foreach ($reportList as $key => $repInfo) { - foreach ($colList as $col => $dbCol) { - $rankDiff[$col] = ''; - } - - foreach ($colList as $col => $dbCol) { - if ($i > 0) { - $signVal = -1; - $greaterClass = 'green'; - $lessClass = 'red'; - if($col == 'alexa'){ - $signVal = 1; - $greaterClass = 'green'; - $lessClass = 'red'; - } - $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * $signVal; - if ($rankDiff[$col] > 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - }elseif ($rankDiff[$col] < 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - } - } - $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; - } - - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = $repInfo[$dbCol]; - } - - $i++; - } - - $this->set('list', array_reverse($reportList, true)); - $this->render('rank/rankreport'); - } - - - # func to show reports for a particular website - function __getWebsiteRankReport($websiteId, $fromTime, $toTime) { - - $fromTimeLabel = date('Y-m-d', $fromTime); - $toTimeLabel = date('Y-m-d', $toTime); - $sql = "select s.* ,w.name - from rankresults s,websites w - where s.website_id=w.id - and s.website_id=$websiteId - and (FROM_UNIXTIME(result_time, '%Y-%m-%d')='$fromTimeLabel' or FROM_UNIXTIME(result_time, '%Y-%m-%d')='$toTimeLabel') - order by result_time DESC - Limit 0, 2"; - $reportList = $this->db->select($sql); - $reportList = array_reverse($reportList); - - $i = 0; - $colList = array('moz' => 'moz_rank', 'alexa' => 'alexa_rank'); - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = 0; - } - - # loop throgh rank - foreach ($reportList as $key => $repInfo) { - foreach ($colList as $col => $dbCol) { - $rankDiff[$col] = ''; - } - - foreach ($colList as $col => $dbCol) { - if ($i > 0) { - $signVal = -1; - $greaterClass = 'green'; - $lessClass = 'red'; - if($col == 'alexa'){ - $signVal = 1; - $greaterClass = 'green'; - $lessClass = 'red'; - } - $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * $signVal; - if ($rankDiff[$col] > 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - }elseif ($rankDiff[$col] < 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - } - } - $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; - } - - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = $repInfo[$dbCol]; - } - - $i++; - } - - $reportList = array_reverse(array_slice($reportList, count($reportList) - 1)); - return $reportList; - } - -} +render('rank/showquickrank'); + } + + function findQuickRank($searchInfo) { + $urlList = explode("\n", $searchInfo['website_urls']); + $list = array(); + $i = 1; + foreach ($urlList as $url) { + $url = sanitizeData($url); + if(!preg_match('/\w+/', $url)) continue; + if (SP_DEMO) { + if ($i++ > 10) break; + } + + $url = addHttpToUrl($url); + $list[] = str_replace(array("\n", "\r", "\r\n", "\n\r"), "", trim($url)); + } + + $mozRankList = $this->__getMozRank($list); + $this->set('mozRankList', $mozRankList); + + $this->set('list', $list); + $this->render('rank/findquickrank'); + } + + function printGooglePageRank($url){ + $pageRank = $this->__getGooglePageRank($url); + if($pageRank >= 0){ + $imageUrl = SP_IMGPATH."/pr/pr".$pageRank.".gif"; + }else{ + $imageUrl = SP_IMGPATH."/pr/pr.gif"; + } + + print "".$_SESSION['text']['common']['nowebsites']."!
"; + exit; + } + + $urlList = array(); + foreach ($websiteList as $websiteInfo) { + $urlList[] = addHttpToUrl($websiteInfo['url']); + } + + // get moz ranks + $mozRankList = $this->__getMozRank($urlList); + + // loop through each websites + foreach ( $websiteList as $i => $websiteInfo ) { + $websiteUrl = addHttpToUrl($websiteInfo['url']); + $websiteInfo['alexaRank'] = $this->__getAlexaRank($websiteUrl); + $websiteInfo['moz_rank'] = !empty($mozRankList[$i]) ? $mozRankList[$i] : 0; + + $this->saveRankResults($websiteInfo, true); + echo "".$this->spTextRank['Saved rank results of']." $websiteUrl.....
"; + } + } + + # function to save rank details + function saveRankResults($matchInfo, $remove=false) { + $time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + + if($remove){ + $sql = "delete from rankresults where website_id={$matchInfo['id']} and result_time=$time"; + $this->db->query($sql); + } + + $sql = "insert into rankresults(website_id,moz_rank,alexa_rank,result_time) + values({$matchInfo['id']},{$matchInfo['moz_rank']},{$matchInfo['alexaRank']},$time)"; + $this->db->query($sql); + } + + # function check whether reports already saved + function isReportsExists($websiteId, $time) { + $sql = "select website_id from rankresults where website_id=$websiteId and result_time=$time"; + $info = $this->db->select($sql, true); + return empty($info['website_id']) ? false : true; + } + + # func to show reports + function showReports($searchInfo = '') { + + $userId = isLoggedIn(); + if (!empty ($searchInfo['from_time'])) { + $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); + } else { + $fromTime = mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); + } + if (!empty ($searchInfo['to_time'])) { + $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); + } else { + $toTime = @mktime(); + } + $this->set('fromTime', date('Y-m-d', $fromTime)); + $this->set('toTime', date('Y-m-d', $toTime)); + + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + + $conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId"; + $sql = "select s.* ,w.name + from rankresults s,websites w + where s.website_id=w.id + and result_time>= $fromTime and result_time<=$toTime $conditions + order by result_time"; + $reportList = $this->db->select($sql); + + $i = 0; + $colList = array('moz' => 'moz_rank', 'alexa' => 'alexa_rank'); + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = 0; + } + + # loop throgh rank + foreach ($reportList as $key => $repInfo) { + foreach ($colList as $col => $dbCol) { + $rankDiff[$col] = ''; + } + + foreach ($colList as $col => $dbCol) { + if ($i > 0) { + $signVal = -1; + $greaterClass = 'green'; + $lessClass = 'red'; + if($col == 'alexa'){ + $signVal = 1; + $greaterClass = 'green'; + $lessClass = 'red'; + } + $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * $signVal; + if ($rankDiff[$col] > 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + }elseif ($rankDiff[$col] < 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + } + } + $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; + } + + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = $repInfo[$dbCol]; + } + + $i++; + } + + $this->set('list', array_reverse($reportList, true)); + $this->render('rank/rankreport'); + } + + + # func to show reports for a particular website + function __getWebsiteRankReport($websiteId, $fromTime, $toTime) { + + $fromTimeLabel = date('Y-m-d', $fromTime); + $toTimeLabel = date('Y-m-d', $toTime); + $sql = "select s.* ,w.name + from rankresults s,websites w + where s.website_id=w.id + and s.website_id=$websiteId + and (FROM_UNIXTIME(result_time, '%Y-%m-%d')='$fromTimeLabel' or FROM_UNIXTIME(result_time, '%Y-%m-%d')='$toTimeLabel') + order by result_time DESC + Limit 0, 2"; + $reportList = $this->db->select($sql); + $reportList = array_reverse($reportList); + + $i = 0; + $colList = array('moz' => 'moz_rank', 'alexa' => 'alexa_rank'); + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = 0; + } + + # loop throgh rank + foreach ($reportList as $key => $repInfo) { + foreach ($colList as $col => $dbCol) { + $rankDiff[$col] = ''; + } + + foreach ($colList as $col => $dbCol) { + if ($i > 0) { + $signVal = -1; + $greaterClass = 'green'; + $lessClass = 'red'; + if($col == 'alexa'){ + $signVal = 1; + $greaterClass = 'green'; + $lessClass = 'red'; + } + $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * $signVal; + if ($rankDiff[$col] > 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + }elseif ($rankDiff[$col] < 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + } + } + $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; + } + + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = $repInfo[$dbCol]; + } + + $i++; + } + + $reportList = array_reverse(array_slice($reportList, count($reportList) - 1)); + return $reportList; + } + +} ?> \ No newline at end of file diff --git a/controllers/report.ctrl.php b/controllers/report.ctrl.php index 5e4a98cd..56dc63fa 100644 --- a/controllers/report.ctrl.php +++ b/controllers/report.ctrl.php @@ -1,1381 +1,1381 @@ -seLIst)){ - $seController = New SearchEngineController(); - $this->seLIst = $seController->__getAllSearchEngines(); - } - - $fromTimeLabel = date('Y-m-d', $fromTime); - $toTimeLabel = date('Y-m-d', $toTime); - foreach($this->seLIst as $seInfo){ - $sql = "select min(rank) as rank,result_date from searchresults - where keyword_id=$keywordId and searchengine_id=".$seInfo['id']." - and (result_date='$fromTimeLabel' or result_date='$toTimeLabel') - group by result_date order by result_date DESC limit 0, 2"; - $reportList = $this->db->select($sql); - $reportList = array_reverse($reportList); - - $prevRank = 0; - $i = 0; - foreach ($reportList as $key => $repInfo) { - $rankDiff = ''; - if ($i > 0) { - $rankDiff = $prevRank - $repInfo['rank']; - if ($rankDiff > 0) { - $rankDiff = $apiCall ? $rankDiff : "($rankDiff)"; - } elseif ($rankDiff < 0) { - $rankDiff = $apiCall ? $rankDiff : "($rankDiff)"; - } - } - $positionInfo[$seInfo['id']]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff; - $positionInfo[$seInfo['id']]['rank'] = $repInfo['rank']; - $positionInfo[$seInfo['id']][$repInfo['result_date']] = $repInfo['rank']; - $prevRank = $repInfo['rank']; - $i++; - } - } - - return $positionInfo; - } - - - # func to show keyword report summary - function showKeywordReportSummary($searchInfo = '') { - - $userId = isLoggedIn(); - $exportVersion = false; - switch($searchInfo['doc_type']){ - - case "export": - $exportVersion = true; - $exportContent = ""; - break; - - case "pdf": - $this->set('pdfVersion', true); - break; - - case "print": - $this->set('printVersion', true); - break; - } - - // verify reports generated for user or not - $repSetInfo = $this->getUserReportSettings($userId); - $repGenerated = (date('y-m-d') === date("y-m-d", $repSetInfo['last_generated'])) ? true : false; - - if (!empty ($searchInfo['from_time'])) { - $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); - } else { - $intervalDays = $repGenerated ? 7 : 8; - $fromTime = mktime(0, 0, 0, date('m'), date('d') - $intervalDays, date('Y')); - } - - if (!empty ($searchInfo['to_time'])) { - $toTime = strtotime($searchInfo['to_time'] . ' 00:00:00'); - } else { - $intervalDays = $repGenerated ? 0 : 1; - $toTime = mktime(0, 0, 0, date('m'), date('d') - $intervalDays, date('Y')); - } - - $fromTimeTxt = date('Y-m-d', $fromTime); - $toTimeTxt = date('Y-m-d', $toTime); - $this->set('fromTime', $fromTimeTxt); - $this->set('toTime', $toTimeTxt); - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = isset($searchInfo['website_id']) ? $searchInfo['website_id'] : $websiteList[0]['id']; - $websiteId = intval($websiteId); - $this->set('websiteId', $websiteId); - - $websiteUrl = ""; - foreach ($websiteList as $websiteInfo) { - if ($websiteInfo['id'] == $websiteId) { - $websiteUrl = $websiteInfo['url']; - break; - } - } - $this->set('websiteUrl', $websiteUrl); - - $seController = New SearchEngineController(); - $this->seLIst = $seController->__getAllSearchEngines(); - $this->set('seList', $this->seLIst); - - // to find order col - if (!empty($searchInfo['order_col'])) { - $orderCol = $searchInfo['order_col']; - $orderVal = $searchInfo['order_val']; - } else { - $orderCol = $this->seLIst[0]['id']; - $orderVal = 'ASC'; - } - - $this->set('orderCol', $orderCol); - $this->set('orderVal', $orderVal); - $scriptPath = SP_WEBPATH."/reports.php?sec=reportsum&website_id=$websiteId"; - $scriptPath .= "&from_time=$fromTimeTxt&to_time=$toTimeTxt&search_name=" . $searchInfo['search_name']; - $scriptPath .= "&order_col=$orderCol&order_val=$orderVal"; - $keywordController = New KeywordController(); - - if (in_array($searchInfo['doc_type'], array("pdf", "export"))) { - $list = $keywordController->__getAllKeywords($userId, $websiteId, true, true, $orderVal, $searchInfo['search_name']); - } else { - - $conditions = " and w.status=1 and k.status=1"; - $conditions .= isAdmin() ? "" : " and w.user_id=$userId"; - $conditions .= !empty($websiteId) ? " and w.id=$websiteId" : ""; - $conditions .= !empty($searchInfo['search_name']) ? " and k.name like '%".addslashes($searchInfo['search_name'])."%'" : ""; - - $subSql = "select [col] from keywords k,searchresults r, websites w - where k.id=r.keyword_id and k.website_id=w.id $conditions - and r.searchengine_id=".intval($orderCol)." and r.result_date='" . addslashes($toTimeTxt) . "' - group by k.id"; - - $unionOrderCol = ($orderCol == "keyword") ? "name" : "rank"; - $sql = "(". str_replace("[col]", "k.id,k.name,min(rank) rank,w.name website,w.url weburl", $subSql) .") - UNION - (select k.id,k.name,1000,w.name website,w.url weburl - from keywords k, websites w - where w.id=k.website_id $conditions and k.id not in - (". str_replace("[col]", "distinct(k.id)", $subSql) .")) - order by $unionOrderCol $orderVal"; - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', ""); - $this->set('pagingDiv', $pagingDiv); - $this->set('pageNo', $searchInfo['pageno']); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - - # set keywords list - $list = $this->db->select($sql); - - } - - $indexList = array(); - foreach($list as $keywordInfo){ - $positionInfo = $this->__getKeywordSearchReport($keywordInfo['id'], $fromTime, $toTime, true); - - // check whether the sorting search engine is there - $indexList[$keywordInfo['id']] = empty($positionInfo[$orderCol][$toTimeTxt]) ? 10000 : $positionInfo[$orderCol][$toTimeTxt]; - - $keywordInfo['position_info'] = $positionInfo; - $keywordList[$keywordInfo['id']] = $keywordInfo; - } - - // sort array according the value - if ($orderCol != 'keyword') { - if ($orderVal == 'DESC') { - arsort($indexList); - } else { - asort($indexList); - } - } - $this->set('indexList', $indexList); - - if ($exportVersion) { - $spText = $_SESSION['text']; - $reportHeading = $this->spTextTools['Keyword Position Summary']."(".date('Y-m-d', $fromTime)." - ".date('Y-m-d', $toTime).")"; - $exportContent .= createExportContent( array('', $reportHeading, '')); - $exportContent .= createExportContent( array()); - $headList = array($spText['common']['Website'], $spText['common']['Keyword']); - - $pTxt = str_replace("-", "/", substr($fromTimeTxt, -5)); - $cTxt = str_replace("-", "/", substr($toTimeTxt, -5)); - foreach ($this->seLIst as $seInfo) { - $domainTxt = str_replace("www.", "", $seInfo['domain']); - $headList[] = $domainTxt . "($cTxt)"; - $headList[] = $domainTxt . "($pTxt)"; - $headList[] = $domainTxt . "(+/-)"; - } - - $exportContent .= createExportContent( $headList); - foreach($indexList as $keywordId => $rankValue){ - $listInfo = $keywordList[$keywordId]; - $positionInfo = $listInfo['position_info']; - - $valueList = array($listInfo['weburl'], $listInfo['name']); - foreach ($this->seLIst as $index => $seInfo){ - - $rankInfo = $positionInfo[$seInfo['id']]; - $prevRank = isset($rankInfo[$fromTimeTxt]) ? $rankInfo[$fromTimeTxt] : ""; - $currRank = isset($rankInfo[$toTimeTxt]) ? $rankInfo[$toTimeTxt] : ""; - $rankDiff = ""; - - // if both ranks are existing - if ($prevRank != '' && $currRank != '') { - $rankDiff = $prevRank - $currRank; - } - - $valueList[] = $currRank; - $valueList[] = $prevRank; - $valueList[] = $rankDiff; - } - - $exportContent .= createExportContent( $valueList); - } - exportToCsv('keyword_report_summary', $exportContent); - } else { - $this->set('list', $keywordList); - - // if pdf export - if ($searchInfo['doc_type'] == "pdf") { - exportToPdf($this->getViewContent('report/reportsummary'), "keyword_report_summary_$fromTimeTxt-$toTimeTxt.pdf"); - } else { - $this->set('searchInfo', $searchInfo); - $this->render('report/reportsummary'); - } - } - } - - # func to show reports - function showReports($searchInfo = '') { - - $userId = isLoggedIn(); - if (!empty ($searchInfo['from_time'])) { - $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); - } else { - $fromTime = @mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); - } - if (!empty ($searchInfo['to_time'])) { - $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); - } else { - $toTime = @mktime(); - } - - $fromTimeDate = date('Y-m-d', $fromTime); - $toTimeDate = date('Y-m-d', $toTime); - $this->set('fromTime', $fromTimeDate); - $this->set('toTime', $toTimeDate); - - $keywordController = New KeywordController(); - if(!empty($searchInfo['keyword_id']) && !empty($searchInfo['rep'])){ - - $searchInfo['keyword_id'] = intval($searchInfo['keyword_id']); - $keywordInfo = $keywordController->__getKeywordInfo($searchInfo['keyword_id']); - $searchInfo['website_id'] = $keywordInfo['website_id']; - } - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); - $this->set('websiteId', $websiteId); - - $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); - $this->set('keywordList', $keywordList); - $keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : $searchInfo['keyword_id']; - $this->set('keywordId', $keywordId); - - $seController = New SearchEngineController(); - $seList = $seController->__getAllSearchEngines(); - $this->set('seList', $seList); - $seId = empty ($searchInfo['se_id']) ? $seList[0]['id'] : intval($searchInfo['se_id']); - $this->set('seId', $seId); - $this->set('seInfo', $seController->__getsearchEngineInfo($seId)); - - $conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId"; - $conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId"; - $sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd - where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<='$toTimeDate' $conditions - order by s.result_date"; - $repList = $this->db->select($sql); - - $reportList = array (); - foreach ($repList as $repInfo) { - $var = 'se' . $seId . $repInfo['keyword_id'] . $repInfo['result_date']; - if (empty ($reportList[$var])) { - $reportList[$var] = $repInfo; - } else { - if ($repInfo['rank'] < $reportList[$var]['rank']) { - $reportList[$var] = $repInfo; - } - } - - } - - $prevRank = 0; - $i = 0; - foreach ($reportList as $key => $repInfo) { - $rankDiff = ''; - if ($i > 0) { - $rankDiff = $prevRank - $repInfo['rank']; - if ($rankDiff > 0) { - $rankDiff = "($rankDiff)"; - } - elseif ($rankDiff < 0) { - $rankDiff = "($rankDiff)"; - } - } - $reportList[$key]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff; - $prevRank = $repInfo['rank']; - $i++; - } - - $this->set('list', array_reverse($reportList, true)); - $this->render('report/report'); - } - - # func to show reports in a time - function showTimeReport($searchInfo = '') { - - $fromTime = addslashes($searchInfo['time']); - $toTime = $fromTime + (3600 * 24); - $keywordId = intval($searchInfo['keyId']); - $seId = intval($searchInfo['seId']); - $seController = New SearchEngineController(); - $this->set('seInfo', $seController->__getsearchEngineInfo($seId)); - - $conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId"; - $conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId"; - - $fromTimeDate = date('Y-m-d', $fromTime); - $toTimeDate = date('Y-m-d', $toTime); - $sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd - where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<'$toTimeDate' $conditions - order by s.rank"; - $reportList = $this->db->select($sql); - $this->set('list', $reportList); - $this->render('report/timereport'); - } - - # func to show graphical reports - function showGraphicalReports($searchInfo = '') { - - $userId = isLoggedIn(); - if (!empty ($searchInfo['from_time'])) { - $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); - } else { - $fromTime = @mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); - } - if (!empty ($searchInfo['to_time'])) { - $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); - } else { - $toTime = @mktime(); - } - $this->set('fromTime', date('Y-m-d', $fromTime)); - $this->set('toTime', date('Y-m-d', $toTime)); - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); - $this->set('websiteId', $websiteId); - - $keywordController = New KeywordController(); - $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); - $this->set('keywordList', $keywordList); - $keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : intval($searchInfo['keyword_id']); - $this->set('keywordId', $keywordId); - - $seController = New SearchEngineController(); - $seList = $seController->__getAllSearchEngines(); - $this->set('seList', $seList); - $seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']); - $this->set('seId', $seId); - $this->set('seNull', true); - $this->set('graphUrl', "graphical-reports.php?sec=graph&fromTime=$fromTime&toTime=$toTime&keywordId=$keywordId&seId=$seId"); - - $this->render('report/graphicalreport'); - } - - # function to show an message in graph when no records exist - function showMessageAsImage($msg='', $width=700, $height=30, $red=233, $green=14, $blue=91) { - - $im = imagecreate($width, $height); - $bgColor = imagecolorallocate($im, 245, 248, 250); - $textColor = imagecolorallocate($im, 233, 14, 91); - $fontFile = ($_SESSION['lang_code'] == 'ja') ? "fonts/M+1P+IPAG.ttf" : "fonts/tahoma.ttf"; - imagettftext($im, 10, 0, 260, 20, $textColor, $fontFile, $msg); - imagepng($im); - imagedestroy($im); - exit; - } - - # function to show graph - function showGraph($searchInfo = '') { - - $fromTimeDate = date('Y-m-d', $searchInfo['fromTime']); - $toTimeDate = date('Y-m-d', $searchInfo['toTime']); - $conditions = empty ($searchInfo['keywordId']) ? "" : " and s.keyword_id=".intval($searchInfo['keywordId']); - $conditions .= empty ($searchInfo['seId']) ? "" : " and s.searchengine_id=".intval($searchInfo['seId']); - $sql = "select s.*,se.domain from searchresults s,searchengines se - where s.searchengine_id=se.id and result_date>='$fromTimeDate' and result_date<='$toTimeDate' - $conditions order by s.result_date"; - $repList = $this->db->select($sql); - $reportList = array (); - $seList = array(); - foreach ($repList as $repInfo) { - $var = $repInfo['searchengine_id'] . $repInfo['keyword_id'] . $repInfo['result_date']; - if (empty ($reportList[$var])) { - $reportList[$var] = $repInfo; - } else { - if ($repInfo['rank'] < $reportList[$var]['rank']) { - $reportList[$var] = $repInfo; - } - } - - if(empty($seList[$repInfo['searchengine_id']])){ - $seList[$repInfo['searchengine_id']] = $repInfo['domain']; - } - } - asort($seList); - - $dataList = array(); - $maxValue = 0; - foreach($reportList as $repInfo){ - $seId = $repInfo['searchengine_id']; - $dataList[$repInfo['result_date']][$seId] = $repInfo['rank']; - $maxValue = ($repInfo['rank'] > $maxValue) ? $repInfo['rank'] : $maxValue; - } - - // check whether the records are available for drawing graph - if(empty($dataList) || empty($maxValue)) { - $kpText = ($_SESSION['lang_code'] == 'ja') ? $_SESSION['text']['common']['No Records Found']."!" : "No Records Found!"; - $this->showMessageAsImage($kpText); - } - - # Dataset definition - $dataSet = new pData; - foreach($dataList as $dataInfo){ - $i = 1; - foreach($seList as $seId => $seVal){ - $val = empty($dataInfo[$seId]) ? 0 : $dataInfo[$seId]; - $dataSet->AddPoint($val, "Serie".$i++); - } - } - - $i = 1; - foreach($seList as $seDomain){ - $dataSet->AddSerie("Serie$i"); - $dataSet->SetSerieName($seDomain, "Serie$i"); - $i++; - } - - $serieCount = count($seList) + 1; - $dataSet->AddPoint(array_keys($dataList), "Serie$serieCount"); - $dataSet->SetAbsciseLabelSerie("Serie$serieCount"); - - # if language is japanese - if ($_SESSION['lang_code'] == 'ja') { - $fontFile = "fonts/M+1P+IPAG.ttf"; - $dataSet->SetXAxisName($_SESSION['text']['common']["Date"]); - $dataSet->SetYAxisName($_SESSION['text']['common']["Rank"]); - } else { - $fontFile = "fonts/tahoma.ttf"; - $dataSet->SetXAxisName("Date"); - $dataSet->SetYAxisName("Rank"); - } - - /* commented to fix invalid date in graphical reports x axis issue */ - // $dataSet->SetXAxisFormat("date"); - - # Initialise the graph - $chart = new pChart(720, 520); - $chart->setFixedScale($maxValue, 1); - $chart->setFontProperties($fontFile, 8); - $chart->setGraphArea(85, 30, 670, 425); - $chart->drawFilledRoundedRectangle(7, 7, 713, 513, 5, 240, 240, 240); - $chart->drawRoundedRectangle(5, 5, 715, 515, 5, 230, 230, 230); - - $chart->drawGraphArea(255, 255, 255, TRUE); - $getData = $dataSet->GetData(); - $getDataDes = $dataSet->GetDataDescription(); - $chart->drawScale($getData, $getDataDes, SCALE_NORMAL, 150, 150, 150, TRUE, 90, 2); - $chart->drawGrid(4, TRUE, 230, 230, 230, 50); - - # Draw the 0 line - $chart->setFontProperties($fontFile, 6); - $chart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); - - # Draw the line graph - $getData = $dataSet->GetData(); - $getDataDes = $dataSet->GetDataDescription(); - $chart->drawLineGraph($getData, $getDataDes); - $getData = $dataSet->GetData(); - $getDataDes = $dataSet->GetDataDescription(); - $chart->drawPlotGraph($getData, $getDataDes, 3, 2, 255, 255, 255); - - $j = 1; - $chart->setFontProperties($fontFile, 10); - foreach($seList as $seDomain){ - $getData = $dataSet->GetData(); - $getDataDes = $dataSet->GetDataDescription(); - $chart->writeValues($getData, $getDataDes, "Serie".$j++); - } - - # Finish the graph - $chart->setFontProperties("fonts/tahoma.ttf", 8); - $getDataDes = $dataSet->GetDataDescription(); - $chart->drawLegend(90, 35, $getDataDes, 255, 255, 255); - $chart->setFontProperties($fontFile, 10); - $kpText = ($_SESSION['lang_code'] == 'ja') ? $this->spTextKeyword["Keyword Position Report"] : "Keyword Position Report"; - $chart->drawTitle(60, 22, $kpText, 50, 50, 50, 585); - $chart->stroke(); - } - - # func to show genearte reports interface - function showGenerateReports($searchInfo = '') { - - $userId = isLoggedIn(); - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty ($searchInfo['website_id']) ? '' : $searchInfo['website_id']; - $this->set('websiteId', $websiteId); - - $keywordController = New KeywordController(); - $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); - $this->set('keywordList', $keywordList); - $this->set('keyNull', true); - $keywordId = empty ($searchInfo['keyword_id']) ? '' : $searchInfo['keyword_id']; - $this->set('keywordId', $keywordId); - - $seController = New SearchEngineController(); - $seList = $seController->__getAllSearchEngines(); - $this->set('seList', $seList); - $seId = empty ($searchInfo['se_id']) ? '' : $searchInfo['se_id']; - $this->set('seId', $seId); - $this->set('seNull', true); - $this->set('seStyle', 170); - - $this->render('report/generatereport'); - } - - # func to generate reports - function generateReports( $searchInfo='' ) { - $userId = isLoggedIn(); - $keywordId = empty ($searchInfo['keyword_id']) ? '' : intval($searchInfo['keyword_id']); - $websiteId = empty ($searchInfo['website_id']) ? '' : intval($searchInfo['website_id']); - $seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']); - - $seController = New SearchEngineController(); - $this->seList = $seController->__getAllCrawlFormatedSearchEngines(); - - $sql = "select k.*,w.url from keywords k,websites w where k.website_id=w.id and k.status=1"; - if(!empty($userId) && !isAdmin()) $sql .= " and w.user_id=$userId"; - if(!empty($websiteId)) $sql .= " and k.website_id=$websiteId"; - if(!empty($keywordId)) $sql .= " and k.id=$keywordId"; - $sql .= " order by k.name"; - $keywordList = $this->db->select($sql); - - if(count($keywordList) <= 0){ - echo "".$_SESSION['text']['common']['No Keywords Found']."
"; - exit; - } - - # loop through each keyword - foreach ( $keywordList as $keywordInfo ) { - $this->seFound = 0; - $crawlResult = $this->crawlKeyword($keywordInfo, $seId); - foreach($crawlResult as $sengineId => $matchList){ - if($matchList['status']){ - foreach($matchList['matched'] as $i => $matchInfo){ - $remove = ($i == 0) ? true : false; - $matchInfo['se_id'] = $sengineId; - $matchInfo['keyword_id'] = $keywordInfo['id']; - $this->saveMatchedKeywordInfo($matchInfo, $remove); - } - echo "".$this->spTextKeyword['Successfully crawled keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['results from']." ".$this->seList[$sengineId]['domain'].".....
"; - }else{ - echo "".$this->spTextKeyword['Crawling keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['results from']." ".$this->seList[$sengineId]['domain']." ".$_SESSION['text']['common']['failed']."......
"; - } - } - if(empty($this->seFound)){ - echo "".$_SESSION['text']['common']['Keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['not assigned to required search engines']."........
"; - } +seLIst)){ + $seController = New SearchEngineController(); + $this->seLIst = $seController->__getAllSearchEngines(); + } + + $fromTimeLabel = date('Y-m-d', $fromTime); + $toTimeLabel = date('Y-m-d', $toTime); + foreach($this->seLIst as $seInfo){ + $sql = "select min(rank) as rank,result_date from searchresults + where keyword_id=$keywordId and searchengine_id=".$seInfo['id']." + and (result_date='$fromTimeLabel' or result_date='$toTimeLabel') + group by result_date order by result_date DESC limit 0, 2"; + $reportList = $this->db->select($sql); + $reportList = array_reverse($reportList); + + $prevRank = 0; + $i = 0; + foreach ($reportList as $key => $repInfo) { + $rankDiff = ''; + if ($i > 0) { + $rankDiff = $prevRank - $repInfo['rank']; + if ($rankDiff > 0) { + $rankDiff = $apiCall ? $rankDiff : "($rankDiff)"; + } elseif ($rankDiff < 0) { + $rankDiff = $apiCall ? $rankDiff : "($rankDiff)"; + } + } + $positionInfo[$seInfo['id']]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff; + $positionInfo[$seInfo['id']]['rank'] = $repInfo['rank']; + $positionInfo[$seInfo['id']][$repInfo['result_date']] = $repInfo['rank']; + $prevRank = $repInfo['rank']; + $i++; + } + } + + return $positionInfo; + } + + + # func to show keyword report summary + function showKeywordReportSummary($searchInfo = '') { + + $userId = isLoggedIn(); + $exportVersion = false; + switch($searchInfo['doc_type']){ + + case "export": + $exportVersion = true; + $exportContent = ""; + break; + + case "pdf": + $this->set('pdfVersion', true); + break; + + case "print": + $this->set('printVersion', true); + break; + } + + // verify reports generated for user or not + $repSetInfo = $this->getUserReportSettings($userId); + $repGenerated = (date('y-m-d') === date("y-m-d", $repSetInfo['last_generated'])) ? true : false; + + if (!empty ($searchInfo['from_time'])) { + $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); + } else { + $intervalDays = $repGenerated ? 7 : 8; + $fromTime = mktime(0, 0, 0, date('m'), date('d') - $intervalDays, date('Y')); + } + + if (!empty ($searchInfo['to_time'])) { + $toTime = strtotime($searchInfo['to_time'] . ' 00:00:00'); + } else { + $intervalDays = $repGenerated ? 0 : 1; + $toTime = mktime(0, 0, 0, date('m'), date('d') - $intervalDays, date('Y')); + } + + $fromTimeTxt = date('Y-m-d', $fromTime); + $toTimeTxt = date('Y-m-d', $toTime); + $this->set('fromTime', $fromTimeTxt); + $this->set('toTime', $toTimeTxt); + + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = isset($searchInfo['website_id']) ? $searchInfo['website_id'] : $websiteList[0]['id']; + $websiteId = intval($websiteId); + $this->set('websiteId', $websiteId); + + $websiteUrl = ""; + foreach ($websiteList as $websiteInfo) { + if ($websiteInfo['id'] == $websiteId) { + $websiteUrl = $websiteInfo['url']; + break; + } + } + $this->set('websiteUrl', $websiteUrl); + + $seController = New SearchEngineController(); + $this->seLIst = $seController->__getAllSearchEngines(); + $this->set('seList', $this->seLIst); + + // to find order col + if (!empty($searchInfo['order_col'])) { + $orderCol = $searchInfo['order_col']; + $orderVal = $searchInfo['order_val']; + } else { + $orderCol = $this->seLIst[0]['id']; + $orderVal = 'ASC'; + } + + $this->set('orderCol', $orderCol); + $this->set('orderVal', $orderVal); + $scriptPath = SP_WEBPATH."/reports.php?sec=reportsum&website_id=$websiteId"; + $scriptPath .= "&from_time=$fromTimeTxt&to_time=$toTimeTxt&search_name=" . $searchInfo['search_name']; + $scriptPath .= "&order_col=$orderCol&order_val=$orderVal"; + $keywordController = New KeywordController(); + + if (in_array($searchInfo['doc_type'], array("pdf", "export"))) { + $list = $keywordController->__getAllKeywords($userId, $websiteId, true, true, $orderVal, $searchInfo['search_name']); + } else { + + $conditions = " and w.status=1 and k.status=1"; + $conditions .= isAdmin() ? "" : " and w.user_id=$userId"; + $conditions .= !empty($websiteId) ? " and w.id=$websiteId" : ""; + $conditions .= !empty($searchInfo['search_name']) ? " and k.name like '%".addslashes($searchInfo['search_name'])."%'" : ""; + + $subSql = "select [col] from keywords k,searchresults r, websites w + where k.id=r.keyword_id and k.website_id=w.id $conditions + and r.searchengine_id=".intval($orderCol)." and r.result_date='" . addslashes($toTimeTxt) . "' + group by k.id"; + + $unionOrderCol = ($orderCol == "keyword") ? "name" : "rank"; + $sql = "(". str_replace("[col]", "k.id,k.name,min(rank) rank,w.name website,w.url weburl", $subSql) .") + UNION + (select k.id,k.name,1000,w.name website,w.url weburl + from keywords k, websites w + where w.id=k.website_id $conditions and k.id not in + (". str_replace("[col]", "distinct(k.id)", $subSql) .")) + order by $unionOrderCol $orderVal"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', ""); + $this->set('pagingDiv', $pagingDiv); + $this->set('pageNo', $searchInfo['pageno']); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + # set keywords list + $list = $this->db->select($sql); + + } + + $indexList = array(); + foreach($list as $keywordInfo){ + $positionInfo = $this->__getKeywordSearchReport($keywordInfo['id'], $fromTime, $toTime, true); + + // check whether the sorting search engine is there + $indexList[$keywordInfo['id']] = empty($positionInfo[$orderCol][$toTimeTxt]) ? 10000 : $positionInfo[$orderCol][$toTimeTxt]; + + $keywordInfo['position_info'] = $positionInfo; + $keywordList[$keywordInfo['id']] = $keywordInfo; + } + + // sort array according the value + if ($orderCol != 'keyword') { + if ($orderVal == 'DESC') { + arsort($indexList); + } else { + asort($indexList); + } + } + $this->set('indexList', $indexList); + + if ($exportVersion) { + $spText = $_SESSION['text']; + $reportHeading = $this->spTextTools['Keyword Position Summary']."(".date('Y-m-d', $fromTime)." - ".date('Y-m-d', $toTime).")"; + $exportContent .= createExportContent( array('', $reportHeading, '')); + $exportContent .= createExportContent( array()); + $headList = array($spText['common']['Website'], $spText['common']['Keyword']); + + $pTxt = str_replace("-", "/", substr($fromTimeTxt, -5)); + $cTxt = str_replace("-", "/", substr($toTimeTxt, -5)); + foreach ($this->seLIst as $seInfo) { + $domainTxt = str_replace("www.", "", $seInfo['domain']); + $headList[] = $domainTxt . "($cTxt)"; + $headList[] = $domainTxt . "($pTxt)"; + $headList[] = $domainTxt . "(+/-)"; + } + + $exportContent .= createExportContent( $headList); + foreach($indexList as $keywordId => $rankValue){ + $listInfo = $keywordList[$keywordId]; + $positionInfo = $listInfo['position_info']; + + $valueList = array($listInfo['weburl'], $listInfo['name']); + foreach ($this->seLIst as $index => $seInfo){ + + $rankInfo = $positionInfo[$seInfo['id']]; + $prevRank = isset($rankInfo[$fromTimeTxt]) ? $rankInfo[$fromTimeTxt] : ""; + $currRank = isset($rankInfo[$toTimeTxt]) ? $rankInfo[$toTimeTxt] : ""; + $rankDiff = ""; + + // if both ranks are existing + if ($prevRank != '' && $currRank != '') { + $rankDiff = $prevRank - $currRank; + } + + $valueList[] = $currRank; + $valueList[] = $prevRank; + $valueList[] = $rankDiff; + } + + $exportContent .= createExportContent( $valueList); + } + exportToCsv('keyword_report_summary', $exportContent); + } else { + $this->set('list', $keywordList); + + // if pdf export + if ($searchInfo['doc_type'] == "pdf") { + exportToPdf($this->getViewContent('report/reportsummary'), "keyword_report_summary_$fromTimeTxt-$toTimeTxt.pdf"); + } else { + $this->set('searchInfo', $searchInfo); + $this->render('report/reportsummary'); + } + } + } + + # func to show reports + function showReports($searchInfo = '') { + + $userId = isLoggedIn(); + if (!empty ($searchInfo['from_time'])) { + $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); + } else { + $fromTime = @mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); + } + if (!empty ($searchInfo['to_time'])) { + $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); + } else { + $toTime = @mktime(); + } + + $fromTimeDate = date('Y-m-d', $fromTime); + $toTimeDate = date('Y-m-d', $toTime); + $this->set('fromTime', $fromTimeDate); + $this->set('toTime', $toTimeDate); + + $keywordController = New KeywordController(); + if(!empty($searchInfo['keyword_id']) && !empty($searchInfo['rep'])){ + + $searchInfo['keyword_id'] = intval($searchInfo['keyword_id']); + $keywordInfo = $keywordController->__getKeywordInfo($searchInfo['keyword_id']); + $searchInfo['website_id'] = $keywordInfo['website_id']; + } + + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + + $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); + $this->set('keywordList', $keywordList); + $keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : $searchInfo['keyword_id']; + $this->set('keywordId', $keywordId); + + $seController = New SearchEngineController(); + $seList = $seController->__getAllSearchEngines(); + $this->set('seList', $seList); + $seId = empty ($searchInfo['se_id']) ? $seList[0]['id'] : intval($searchInfo['se_id']); + $this->set('seId', $seId); + $this->set('seInfo', $seController->__getsearchEngineInfo($seId)); + + $conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId"; + $conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId"; + $sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd + where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<='$toTimeDate' $conditions + order by s.result_date"; + $repList = $this->db->select($sql); + + $reportList = array (); + foreach ($repList as $repInfo) { + $var = 'se' . $seId . $repInfo['keyword_id'] . $repInfo['result_date']; + if (empty ($reportList[$var])) { + $reportList[$var] = $repInfo; + } else { + if ($repInfo['rank'] < $reportList[$var]['rank']) { + $reportList[$var] = $repInfo; + } + } + + } + + $prevRank = 0; + $i = 0; + foreach ($reportList as $key => $repInfo) { + $rankDiff = ''; + if ($i > 0) { + $rankDiff = $prevRank - $repInfo['rank']; + if ($rankDiff > 0) { + $rankDiff = "($rankDiff)"; + } + elseif ($rankDiff < 0) { + $rankDiff = "($rankDiff)"; + } + } + $reportList[$key]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff; + $prevRank = $repInfo['rank']; + $i++; + } + + $this->set('list', array_reverse($reportList, true)); + $this->render('report/report'); + } + + # func to show reports in a time + function showTimeReport($searchInfo = '') { + + $fromTime = addslashes($searchInfo['time']); + $toTime = $fromTime + (3600 * 24); + $keywordId = intval($searchInfo['keyId']); + $seId = intval($searchInfo['seId']); + $seController = New SearchEngineController(); + $this->set('seInfo', $seController->__getsearchEngineInfo($seId)); + + $conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId"; + $conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId"; + + $fromTimeDate = date('Y-m-d', $fromTime); + $toTimeDate = date('Y-m-d', $toTime); + $sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd + where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<'$toTimeDate' $conditions + order by s.rank"; + $reportList = $this->db->select($sql); + $this->set('list', $reportList); + $this->render('report/timereport'); + } + + # func to show graphical reports + function showGraphicalReports($searchInfo = '') { + + $userId = isLoggedIn(); + if (!empty ($searchInfo['from_time'])) { + $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); + } else { + $fromTime = @mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); + } + if (!empty ($searchInfo['to_time'])) { + $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); + } else { + $toTime = @mktime(); + } + $this->set('fromTime', date('Y-m-d', $fromTime)); + $this->set('toTime', date('Y-m-d', $toTime)); + + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + + $keywordController = New KeywordController(); + $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); + $this->set('keywordList', $keywordList); + $keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : intval($searchInfo['keyword_id']); + $this->set('keywordId', $keywordId); + + $seController = New SearchEngineController(); + $seList = $seController->__getAllSearchEngines(); + $this->set('seList', $seList); + $seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']); + $this->set('seId', $seId); + $this->set('seNull', true); + $this->set('graphUrl', "graphical-reports.php?sec=graph&fromTime=$fromTime&toTime=$toTime&keywordId=$keywordId&seId=$seId"); + + $this->render('report/graphicalreport'); + } + + # function to show an message in graph when no records exist + function showMessageAsImage($msg='', $width=700, $height=30, $red=233, $green=14, $blue=91) { + + $im = imagecreate($width, $height); + $bgColor = imagecolorallocate($im, 245, 248, 250); + $textColor = imagecolorallocate($im, 233, 14, 91); + $fontFile = ($_SESSION['lang_code'] == 'ja') ? "fonts/M+1P+IPAG.ttf" : "fonts/tahoma.ttf"; + imagettftext($im, 10, 0, 260, 20, $textColor, $fontFile, $msg); + imagepng($im); + imagedestroy($im); + exit; + } + + # function to show graph + function showGraph($searchInfo = '') { + + $fromTimeDate = date('Y-m-d', $searchInfo['fromTime']); + $toTimeDate = date('Y-m-d', $searchInfo['toTime']); + $conditions = empty ($searchInfo['keywordId']) ? "" : " and s.keyword_id=".intval($searchInfo['keywordId']); + $conditions .= empty ($searchInfo['seId']) ? "" : " and s.searchengine_id=".intval($searchInfo['seId']); + $sql = "select s.*,se.domain from searchresults s,searchengines se + where s.searchengine_id=se.id and result_date>='$fromTimeDate' and result_date<='$toTimeDate' + $conditions order by s.result_date"; + $repList = $this->db->select($sql); + $reportList = array (); + $seList = array(); + foreach ($repList as $repInfo) { + $var = $repInfo['searchengine_id'] . $repInfo['keyword_id'] . $repInfo['result_date']; + if (empty ($reportList[$var])) { + $reportList[$var] = $repInfo; + } else { + if ($repInfo['rank'] < $reportList[$var]['rank']) { + $reportList[$var] = $repInfo; + } + } + + if(empty($seList[$repInfo['searchengine_id']])){ + $seList[$repInfo['searchengine_id']] = $repInfo['domain']; + } + } + asort($seList); + + $dataList = array(); + $maxValue = 0; + foreach($reportList as $repInfo){ + $seId = $repInfo['searchengine_id']; + $dataList[$repInfo['result_date']][$seId] = $repInfo['rank']; + $maxValue = ($repInfo['rank'] > $maxValue) ? $repInfo['rank'] : $maxValue; + } + + // check whether the records are available for drawing graph + if(empty($dataList) || empty($maxValue)) { + $kpText = ($_SESSION['lang_code'] == 'ja') ? $_SESSION['text']['common']['No Records Found']."!" : "No Records Found!"; + $this->showMessageAsImage($kpText); + } + + # Dataset definition + $dataSet = new pData; + foreach($dataList as $dataInfo){ + $i = 1; + foreach($seList as $seId => $seVal){ + $val = empty($dataInfo[$seId]) ? 0 : $dataInfo[$seId]; + $dataSet->AddPoint($val, "Serie".$i++); + } + } + + $i = 1; + foreach($seList as $seDomain){ + $dataSet->AddSerie("Serie$i"); + $dataSet->SetSerieName($seDomain, "Serie$i"); + $i++; + } + + $serieCount = count($seList) + 1; + $dataSet->AddPoint(array_keys($dataList), "Serie$serieCount"); + $dataSet->SetAbsciseLabelSerie("Serie$serieCount"); + + # if language is japanese + if ($_SESSION['lang_code'] == 'ja') { + $fontFile = "fonts/M+1P+IPAG.ttf"; + $dataSet->SetXAxisName($_SESSION['text']['common']["Date"]); + $dataSet->SetYAxisName($_SESSION['text']['common']["Rank"]); + } else { + $fontFile = "fonts/tahoma.ttf"; + $dataSet->SetXAxisName("Date"); + $dataSet->SetYAxisName("Rank"); + } + + /* commented to fix invalid date in graphical reports x axis issue */ + // $dataSet->SetXAxisFormat("date"); + + # Initialise the graph + $chart = new pChart(720, 520); + $chart->setFixedScale($maxValue, 1); + $chart->setFontProperties($fontFile, 8); + $chart->setGraphArea(85, 30, 670, 425); + $chart->drawFilledRoundedRectangle(7, 7, 713, 513, 5, 240, 240, 240); + $chart->drawRoundedRectangle(5, 5, 715, 515, 5, 230, 230, 230); + + $chart->drawGraphArea(255, 255, 255, TRUE); + $getData = $dataSet->GetData(); + $getDataDes = $dataSet->GetDataDescription(); + $chart->drawScale($getData, $getDataDes, SCALE_NORMAL, 150, 150, 150, TRUE, 90, 2); + $chart->drawGrid(4, TRUE, 230, 230, 230, 50); + + # Draw the 0 line + $chart->setFontProperties($fontFile, 6); + $chart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); + + # Draw the line graph + $getData = $dataSet->GetData(); + $getDataDes = $dataSet->GetDataDescription(); + $chart->drawLineGraph($getData, $getDataDes); + $getData = $dataSet->GetData(); + $getDataDes = $dataSet->GetDataDescription(); + $chart->drawPlotGraph($getData, $getDataDes, 3, 2, 255, 255, 255); + + $j = 1; + $chart->setFontProperties($fontFile, 10); + foreach($seList as $seDomain){ + $getData = $dataSet->GetData(); + $getDataDes = $dataSet->GetDataDescription(); + $chart->writeValues($getData, $getDataDes, "Serie".$j++); + } + + # Finish the graph + $chart->setFontProperties("fonts/tahoma.ttf", 8); + $getDataDes = $dataSet->GetDataDescription(); + $chart->drawLegend(90, 35, $getDataDes, 255, 255, 255); + $chart->setFontProperties($fontFile, 10); + $kpText = ($_SESSION['lang_code'] == 'ja') ? $this->spTextKeyword["Keyword Position Report"] : "Keyword Position Report"; + $chart->drawTitle(60, 22, $kpText, 50, 50, 50, 585); + $chart->stroke(); + } + + # func to show genearte reports interface + function showGenerateReports($searchInfo = '') { + + $userId = isLoggedIn(); + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? '' : $searchInfo['website_id']; + $this->set('websiteId', $websiteId); + + $keywordController = New KeywordController(); + $keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true); + $this->set('keywordList', $keywordList); + $this->set('keyNull', true); + $keywordId = empty ($searchInfo['keyword_id']) ? '' : $searchInfo['keyword_id']; + $this->set('keywordId', $keywordId); + + $seController = New SearchEngineController(); + $seList = $seController->__getAllSearchEngines(); + $this->set('seList', $seList); + $seId = empty ($searchInfo['se_id']) ? '' : $searchInfo['se_id']; + $this->set('seId', $seId); + $this->set('seNull', true); + $this->set('seStyle', 170); + + $this->render('report/generatereport'); + } + + # func to generate reports + function generateReports( $searchInfo='' ) { + $userId = isLoggedIn(); + $keywordId = empty ($searchInfo['keyword_id']) ? '' : intval($searchInfo['keyword_id']); + $websiteId = empty ($searchInfo['website_id']) ? '' : intval($searchInfo['website_id']); + $seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']); + + $seController = New SearchEngineController(); + $this->seList = $seController->__getAllCrawlFormatedSearchEngines(); + + $sql = "select k.*,w.url from keywords k,websites w where k.website_id=w.id and k.status=1"; + if(!empty($userId) && !isAdmin()) $sql .= " and w.user_id=$userId"; + if(!empty($websiteId)) $sql .= " and k.website_id=$websiteId"; + if(!empty($keywordId)) $sql .= " and k.id=$keywordId"; + $sql .= " order by k.name"; + $keywordList = $this->db->select($sql); + + if(count($keywordList) <= 0){ + echo "".$_SESSION['text']['common']['No Keywords Found']."
"; + exit; + } + + # loop through each keyword + foreach ( $keywordList as $keywordInfo ) { + $this->seFound = 0; + $crawlResult = $this->crawlKeyword($keywordInfo, $seId); + foreach($crawlResult as $sengineId => $matchList){ + if($matchList['status']){ + foreach($matchList['matched'] as $i => $matchInfo){ + $remove = ($i == 0) ? true : false; + $matchInfo['se_id'] = $sengineId; + $matchInfo['keyword_id'] = $keywordInfo['id']; + $this->saveMatchedKeywordInfo($matchInfo, $remove); + } + echo "".$this->spTextKeyword['Successfully crawled keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['results from']." ".$this->seList[$sengineId]['domain'].".....
"; + }else{ + echo "".$this->spTextKeyword['Crawling keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['results from']." ".$this->seList[$sengineId]['domain']." ".$_SESSION['text']['common']['failed']."......
"; + } + } + if(empty($this->seFound)){ + echo "".$_SESSION['text']['common']['Keyword']." {$keywordInfo['name']} ".$this->spTextKeyword['not assigned to required search engines']."........
"; + } sleep(SP_CRAWL_DELAY); } - } - - # function to format pagecontent - function formatPageContent($seInfoId, $pageContent) { - if (!empty($this->seList[$seInfoId]['from_pattern']) && $this->seList[$seInfoId]['to_pattern']) { - $pattern = $this->seList[$seInfoId]['from_pattern']."(.*)".$this->seList[$seInfoId]['to_pattern']; - if (preg_match("/$pattern/is", $pageContent, $matches)) { - if (!empty($matches[1])) { - $pageContent = $matches[1]; - } - } - } - return $pageContent; - } - - # func to crawl keyword - function crawlKeyword( $keywordInfo, $seId='', $cron=false, $removeDuplicate=true) { - $crawlResult = array(); - $websiteUrl = formatUrl($keywordInfo['url'], false); - if(empty($websiteUrl)) return $crawlResult; - if(empty($keywordInfo['name'])) return $crawlResult; - - $time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - $seList = explode(':', $keywordInfo['searchengines']); - foreach($seList as $seInfoId){ - - // function to execute only passed search engine - if(!empty($seId) && ($seInfoId != $seId)) continue; - - // if search engine not found continue - if (empty($this->seList[$seInfoId])) continue; - - $this->seFound = 1; - - // if execution from cron check whether cron already executed - /*if ($cron) { - if (SP_MULTIPLE_CRON_EXEC && $this->isCronExecuted($keywordInfo['id'], $seInfoId, $time)) continue; - }*/ - - $searchUrl = str_replace('[--keyword--]', urlencode(stripslashes($keywordInfo['name'])), $this->seList[$seInfoId]['url']); - $searchUrl = str_replace('[--lang--]', $keywordInfo['lang_code'], $searchUrl); - $searchUrl = str_replace('[--country--]', $keywordInfo['country_code'], $searchUrl); - if (empty($keywordInfo['country_code']) && stristr($searchUrl, '&cr=country&')) { - $searchUrl = str_replace('&cr=country&', '&cr=&', $searchUrl); - } - $seUrl = str_replace('[--start--]', $this->seList[$seInfoId]['start'], $searchUrl); - - // if google add special parameters - $isGoogle = false; - if (stristr($this->seList[$seInfoId]['url'], 'google')) { - $isGoogle = true; - $seUrl .= "&ie=utf-8&pws=0&gl=".$keywordInfo['country_code']; - } - - if(!empty($this->seList[$seInfoId]['cookie_send'])){ - $this->seList[$seInfoId]['cookie_send'] = str_replace('[--lang--]', $keywordInfo['lang_code'], $this->seList[$seInfoId]['cookie_send']); - $this->spider->_CURLOPT_COOKIE = $this->seList[$seInfoId]['cookie_send']; - } - - $result = $this->spider->getContent($seUrl); - $pageContent = $this->formatPageContent($seInfoId, $result['page']); - - $crawlLogCtrl = new CrawlLogController(); - $crawlInfo['crawl_type'] = 'keyword'; - $crawlInfo['ref_id'] = empty($keywordInfo['id']) ? $keywordInfo['name'] : $keywordInfo['id']; - $crawlInfo['subject'] = $seInfoId; - - $seStart = $this->seList[$seInfoId]['start'] + $this->seList[$seInfoId]['start_offset']; - while(empty($result['error']) && ($seStart < $this->seList[$seInfoId]['max_results']) ){ - $logId = $result['log_id']; - $crawlInfo['log_message'] = "Started at: $seStart"; - $crawlLogCtrl->updateCrawlLog($logId, $crawlInfo); - sleep(SP_CRAWL_DELAY); - $seUrl = str_replace('[--start--]', $seStart, $searchUrl); - $result = $this->spider->getContent($seUrl); - $pageContent .= $this->formatPageContent($seInfoId, $result['page']); - $seStart += $this->seList[$seInfoId]['start_offset']; - } - - # to check whether utf8 conversion needed - if(!empty($this->seList[$seInfoId]['encoding'])){ - $pageContent = mb_convert_encoding($pageContent, "UTF-8", $this->seList[$seInfoId]['encoding']); - } - - $crawlStatus = 0; - if(empty($result['error'])){ - - // to update cron that report executed for akeyword on a search engine - if (SP_MULTIPLE_CRON_EXEC && $cron) $this->saveCronTrackInfo($keywordInfo['id'], $seInfoId, $time); - - // verify the urls existing in the result - preg_match_all($this->seList[$seInfoId]['regex'], $pageContent, $matches); - if (!empty($matches[$this->seList[$seInfoId]['url_index']])) { - - $urlList = $matches[$this->seList[$seInfoId]['url_index']]; - $crawlResult[$seInfoId]['matched'] = array(); - $rank = 1; - $previousDomain = ""; - foreach($urlList as $i => $url){ - $url = urldecode(strip_tags($url)); - - // add special condition for baidu - if (stristr($this->seList[$seInfoId]['domain'], "baidu")) { - $url = addHttpToUrl($url); - $url = str_replace("...", "", $url); - } - - if(!preg_match('/^http:\/\/|^https:\/\//i', $url)) continue; - - // check for to remove msn ad links in page - if(stristr($url, 'r.msn.com')) continue; - - // check to remove duplicates from same domain if google is the search engine - if ($removeDuplicate && $isGoogle) { - $currentDomain = parse_url($url, PHP_URL_HOST); - if ($previousDomain == $currentDomain) { - continue; - } - $previousDomain = $currentDomain; - } - - if($this->showAll || stristr($url, $websiteUrl)){ - - if($this->showAll && stristr($url, $websiteUrl)){ - $matchInfo['found'] = 1; - }else{ - $matchInfo['found'] = 0; - } - $matchInfo['url'] = $url; - $matchInfo['title'] = strip_tags($matches[$this->seList[$seInfoId]['title_index']][$i]); - $matchInfo['description'] = strip_tags($matches[$this->seList[$seInfoId]['description_index']][$i]); - $matchInfo['rank'] = $rank; - $crawlResult[$seInfoId]['matched'][] = $matchInfo; - } - $rank++; - } - $crawlStatus = 1; - - } else { - - // set crawl log info - $crawlInfo['crawl_status'] = 0; - $crawlInfo['log_message'] = SearchEngineController::isCaptchInSearchResults($pageContent) ? "Captcha found in search result page" : "Regex not matched error occured while parsing search results!"; - - if(SP_DEBUG){ - echo "Error occured while parsing $seUrl ".formatErrorMsg("Regex not matched
\n")."
Error occured while crawling $seUrl ".formatErrorMsg($result['errmsg']."
\n")."
Error occured while parsing $seUrl ".formatErrorMsg("Regex not matched
\n")."
Error occured while crawling $seUrl ".formatErrorMsg($result['errmsg']."
\n")."
".$_SESSION['text']['common']['nowebsites']."!
"; - exit; - } - - # loop through each websites - foreach ( $websiteList as $websiteInfo ) { - $this->url = $websiteUrl = addHttpToUrl($websiteInfo['url']); - foreach ($this->colList as $col => $dbCol) { - $websiteInfo[$col] = $this->__getSaturationRank($col); - } - - $this->saveRankResults($websiteInfo, true); - echo "".$this->spTextSat['Saved Search Engine Saturation results of']." $websiteUrl.....
"; - } - } - - # function to save rank details - function saveRankResults($matchInfo, $remove=false) { - $time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - - if($remove){ - $sql = "delete from saturationresults where website_id={$matchInfo['id']} and result_time=$time"; - $this->db->query($sql); - } - - $sql = "insert into saturationresults(website_id,google,msn,result_time) - values({$matchInfo['id']},{$matchInfo['google']},{$matchInfo['msn']},$time)"; - $this->db->query($sql); - } - - # function check whether reports already saved - function isReportsExists($websiteId, $time) { - $sql = "select website_id from saturationresults where website_id=$websiteId and result_time=$time"; - $info = $this->db->select($sql, true); - return empty($info['website_id']) ? false : true; - } - - # func to show reports - function showReports($searchInfo = '') { - - $userId = isLoggedIn(); - if (!empty ($searchInfo['from_time'])) { - $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); - } else { - $fromTime = mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); - } - if (!empty ($searchInfo['to_time'])) { - $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); - } else { - $toTime = @mktime(); - } - $this->set('fromTime', date('Y-m-d', $fromTime)); - $this->set('toTime', date('Y-m-d', $toTime)); - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); - $this->set('websiteId', $websiteId); - - $conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId"; - $sql = "select s.* ,w.name - from saturationresults s,websites w - where s.website_id=w.id - and result_time>= $fromTime and result_time<=$toTime $conditions - order by result_time"; - $reportList = $this->db->select($sql); - - $i = 0; - $colList = $this->colList; - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = 0; - } - - # loop throgh rank - foreach ($reportList as $key => $repInfo) { - foreach ($colList as $col => $dbCol) { - $rankDiff[$col] = ''; - } - - foreach ($colList as $col => $dbCol) { - if ($i > 0) { - $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1; - if ($rankDiff[$col] > 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - }elseif ($rankDiff[$col] < 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - } - } - $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; - } - - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = $repInfo[$dbCol]; - } - - $i++; - } - - $websiteInfo = $websiteController->__getWebsiteInfo($websiteId); - $websiteUrl = urldecode($websiteInfo['url']); - $this->set('directLinkList', array( - 'google' => $this->saturationUrlList['google'] . $websiteUrl, - 'msn' => $this->saturationUrlList['msn'] . $websiteUrl, - )); - - $this->set('list', array_reverse($reportList, true)); - $this->render('saturationchecker/saturationreport'); - } - - # func to get reports of saturation of a website - function __getWebsiteSaturationReport($websiteId, $fromTime, $toTime) { - - $fromTimeLabel = date('Y-m-d', $fromTime); - $toTimeLabel = date('Y-m-d', $toTime); - $sql = "select s.* ,w.name from saturationresults s,websites w where s.website_id=w.id and s.website_id=$websiteId - and (FROM_UNIXTIME(result_time, '%Y-%m-%d')='$fromTimeLabel' or FROM_UNIXTIME(result_time, '%Y-%m-%d')='$toTimeLabel') - order by result_time DESC Limit 0,2"; - $reportList = $this->db->select($sql); - $reportList = array_reverse($reportList); - - $i = 0; - $colList = $this->colList; - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = 0; - } - - # loop throgh rank - foreach ($reportList as $key => $repInfo) { - foreach ($colList as $col => $dbCol) { - $rankDiff[$col] = ''; - } - - foreach ($colList as $col => $dbCol) { - if ($i > 0) { - $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1; - if ($rankDiff[$col] > 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - }elseif ($rankDiff[$col] < 0) { - $rankDiff[$col] = "($rankDiff[$col])"; - } - } - $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; - } - - foreach ($colList as $col => $dbCol) { - $prevRank[$col] = $repInfo[$dbCol]; - } - - $i++; - } - - $reportList = array_reverse(array_slice($reportList, count($reportList) - 1)); - return $reportList; - } - -} + 'google', 'msn' => 'msn'); + var $saturationUrlList = array( + 'google' => 'http://www.google.com/search?hl=en&q=site%3A', + 'msn' => 'http://www.bing.com/search?setmkt=en-us&q=site%3A', + ); + + function showSaturationChecker() { + + $this->render('saturationchecker/showsaturationchecker'); + } + + function findSearchEngineSaturation($searchInfo) { + $urlList = explode("\n", $searchInfo['website_urls']); + $list = array(); + $i = 1; + foreach ($urlList as $url) { + $url = sanitizeData($url); + if(!preg_match('/\w+/', $url)) continue; + if (SP_DEMO) { + if ($i++ > 10) break; + } + + $url = addHttpToUrl($url); + $list[] = str_replace(array("\n", "\r", "\r\n", "\n\r"), "", trim($url)); + } + + $this->set('list', $list); + $this->render('saturationchecker/findsearchenginesaturation'); + } + + function printSearchEngineSaturation($saturationInfo){ + $this->url = $saturationInfo['url']; + $saturationCount = $this->__getSaturationRank($saturationInfo['engine']); + $websiteUrl = urldecode($this->url); + $saturationUrl = $this->saturationUrlList[$saturationInfo['engine']] . $websiteUrl; + echo "$saturationCount"; + } + + function __getSaturationRank ($engine) { + if (SP_DEMO && !empty($_SERVER['REQUEST_METHOD'])) return 0; + $saturationCount = 0; + switch ($engine) { + + #google + case 'google': + $url = $this->saturationUrlList[$engine] . urlencode($this->url); + $v = $this->spider->getContent($url); + $pageContent = empty($v['page']) ? '' : $v['page']; + + if (preg_match('/about ([0-9\,]+) result/si', $pageContent, $r)){ + } elseif (preg_match('/".$_SESSION['text']['common']['nowebsites']."!
"; + exit; + } + + # loop through each websites + foreach ( $websiteList as $websiteInfo ) { + $this->url = $websiteUrl = addHttpToUrl($websiteInfo['url']); + foreach ($this->colList as $col => $dbCol) { + $websiteInfo[$col] = $this->__getSaturationRank($col); + } + + $this->saveRankResults($websiteInfo, true); + echo "".$this->spTextSat['Saved Search Engine Saturation results of']." $websiteUrl.....
"; + } + } + + # function to save rank details + function saveRankResults($matchInfo, $remove=false) { + $time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + + if($remove){ + $sql = "delete from saturationresults where website_id={$matchInfo['id']} and result_time=$time"; + $this->db->query($sql); + } + + $sql = "insert into saturationresults(website_id,google,msn,result_time) + values({$matchInfo['id']},{$matchInfo['google']},{$matchInfo['msn']},$time)"; + $this->db->query($sql); + } + + # function check whether reports already saved + function isReportsExists($websiteId, $time) { + $sql = "select website_id from saturationresults where website_id=$websiteId and result_time=$time"; + $info = $this->db->select($sql, true); + return empty($info['website_id']) ? false : true; + } + + # func to show reports + function showReports($searchInfo = '') { + + $userId = isLoggedIn(); + if (!empty ($searchInfo['from_time'])) { + $fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00'); + } else { + $fromTime = mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')); + } + if (!empty ($searchInfo['to_time'])) { + $toTime = strtotime($searchInfo['to_time'] . ' 23:59:59'); + } else { + $toTime = @mktime(); + } + $this->set('fromTime', date('Y-m-d', $fromTime)); + $this->set('toTime', date('Y-m-d', $toTime)); + + $websiteController = New WebsiteController(); + $websiteList = $websiteController->__getAllWebsites($userId, true); + $this->set('websiteList', $websiteList); + $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']); + $this->set('websiteId', $websiteId); + + $conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId"; + $sql = "select s.* ,w.name + from saturationresults s,websites w + where s.website_id=w.id + and result_time>= $fromTime and result_time<=$toTime $conditions + order by result_time"; + $reportList = $this->db->select($sql); + + $i = 0; + $colList = $this->colList; + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = 0; + } + + # loop throgh rank + foreach ($reportList as $key => $repInfo) { + foreach ($colList as $col => $dbCol) { + $rankDiff[$col] = ''; + } + + foreach ($colList as $col => $dbCol) { + if ($i > 0) { + $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1; + if ($rankDiff[$col] > 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + }elseif ($rankDiff[$col] < 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + } + } + $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; + } + + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = $repInfo[$dbCol]; + } + + $i++; + } + + $websiteInfo = $websiteController->__getWebsiteInfo($websiteId); + $websiteUrl = urldecode($websiteInfo['url']); + $this->set('directLinkList', array( + 'google' => $this->saturationUrlList['google'] . $websiteUrl, + 'msn' => $this->saturationUrlList['msn'] . $websiteUrl, + )); + + $this->set('list', array_reverse($reportList, true)); + $this->render('saturationchecker/saturationreport'); + } + + # func to get reports of saturation of a website + function __getWebsiteSaturationReport($websiteId, $fromTime, $toTime) { + + $fromTimeLabel = date('Y-m-d', $fromTime); + $toTimeLabel = date('Y-m-d', $toTime); + $sql = "select s.* ,w.name from saturationresults s,websites w where s.website_id=w.id and s.website_id=$websiteId + and (FROM_UNIXTIME(result_time, '%Y-%m-%d')='$fromTimeLabel' or FROM_UNIXTIME(result_time, '%Y-%m-%d')='$toTimeLabel') + order by result_time DESC Limit 0,2"; + $reportList = $this->db->select($sql); + $reportList = array_reverse($reportList); + + $i = 0; + $colList = $this->colList; + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = 0; + } + + # loop throgh rank + foreach ($reportList as $key => $repInfo) { + foreach ($colList as $col => $dbCol) { + $rankDiff[$col] = ''; + } + + foreach ($colList as $col => $dbCol) { + if ($i > 0) { + $rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1; + if ($rankDiff[$col] > 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + }elseif ($rankDiff[$col] < 0) { + $rankDiff[$col] = "($rankDiff[$col])"; + } + } + $reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col]; + } + + foreach ($colList as $col => $dbCol) { + $prevRank[$col] = $repInfo[$dbCol]; + } + + $i++; + } + + $reportList = array_reverse(array_slice($reportList, count($reportList) - 1)); + return $reportList; + } + +} ?> \ No newline at end of file diff --git a/controllers/searchengine.ctrl.php b/controllers/searchengine.ctrl.php index f559673e..a3c5d881 100644 --- a/controllers/searchengine.ctrl.php +++ b/controllers/searchengine.ctrl.php @@ -1,135 +1,135 @@ -db->select($sql); - return $seList; - } - - # func to get search engine info - function __getsearchEngineInfo($seId){ - $sql = "select * from searchengines where id=$seId"; - $seList = $this->db->select($sql, true); - return $seList; - } - - # func to get all search engines - function __getAllCrawlFormatedSearchEngines(){ - $sql = "select * from searchengines where status=1"; - $list = $this->db->select($sql); - $seList = array(); - foreach($list as $seInfo){ - $seId = $seInfo['id']; - $seInfo['regex'] = "/".$seInfo['regex']."/is"; - $search = array('[--num--]'); - $replace = array($seInfo['no_of_results_page']); - $seInfo['url'] = str_replace($search, $replace, $seInfo['url']); - $seList[$seId] = $seInfo; - } - return $seList; - } - - # func to show search engines - function listSE($info=''){ - $info = sanitizeData($info); - $info['stscheck'] = isset($info['stscheck']) ? intval($info['stscheck']) : 1; - $pageScriptPath = 'searchengine.php?stscheck=' . $info['stscheck']; - $sql = "select * from searchengines where status='{$info['stscheck']}'"; - - // search for search engine name - if (!empty($info['se_name'])) { - $sql .= " and url like '%".addslashes($info['se_name'])."%'"; - $pageScriptPath .= "&se_name=" . $info['se_name']; - } - - $sql .= " order by id"; - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages($pageScriptPath, '', 'scriptDoLoad', 'content', 'layout=ajax'); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - $seList = $this->db->select($sql); - $this->set('seList', $seList); - - $statusList = array( - $_SESSION['text']['common']['Active'] => 1, - $_SESSION['text']['common']['Inactive'] => 0, - ); - - $this->set('statusList', $statusList); - $this->set('info', $info); - $this->set('pageNo', $info['pageno']); - $this->render('searchengine/list', 'ajax'); - } - - # func to change status of search engine - function __changeStatus($seId, $status){ - $seId = intval($seId); - $sql = "update searchengines set status=$status where id=$seId"; - $this->db->query($sql); - } - - # func to delete search engine - function __deleteSearchEngine($seId){ - $seId = intval($seId); - $sql = "delete from searchengines where id=$seId"; - $this->db->query($sql); - - - $sql = "select id from searchresults where searchengine_id=$seId"; - $recordList = $this->db->select($sql); - - if(count($recordList) > 0){ - foreach($recordList as $recordInfo){ - $sql = "delete from searchresultdetails where searchresult_id=".$recordInfo['id']; - $this->db->query($sql); - } - - $sql = "delete from searchresults where searchengine_id=$seId"; - $this->db->query($sql); - } - - } - - # function to check whether captcha found in search engine results - static function isCaptchInSearchResults($searchContent) { - - $captchFound = false; - - // if captcha input field is found - if (stristr($searchContent, 'name="captcha"') || stristr($searchContent, 'id="captcha"')) { - $captchFound = true; - } - - return $captchFound; - } - -} +db->select($sql); + return $seList; + } + + # func to get search engine info + function __getsearchEngineInfo($seId){ + $sql = "select * from searchengines where id=$seId"; + $seList = $this->db->select($sql, true); + return $seList; + } + + # func to get all search engines + function __getAllCrawlFormatedSearchEngines(){ + $sql = "select * from searchengines where status=1"; + $list = $this->db->select($sql); + $seList = array(); + foreach($list as $seInfo){ + $seId = $seInfo['id']; + $seInfo['regex'] = "/".$seInfo['regex']."/is"; + $search = array('[--num--]'); + $replace = array($seInfo['no_of_results_page']); + $seInfo['url'] = str_replace($search, $replace, $seInfo['url']); + $seList[$seId] = $seInfo; + } + return $seList; + } + + # func to show search engines + function listSE($info=''){ + $info = sanitizeData($info); + $info['stscheck'] = isset($info['stscheck']) ? intval($info['stscheck']) : 1; + $pageScriptPath = 'searchengine.php?stscheck=' . $info['stscheck']; + $sql = "select * from searchengines where status='{$info['stscheck']}'"; + + // search for search engine name + if (!empty($info['se_name'])) { + $sql .= " and url like '%".addslashes($info['se_name'])."%'"; + $pageScriptPath .= "&se_name=" . $info['se_name']; + } + + $sql .= " order by id"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages($pageScriptPath, '', 'scriptDoLoad', 'content', 'layout=ajax'); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + $seList = $this->db->select($sql); + $this->set('seList', $seList); + + $statusList = array( + $_SESSION['text']['common']['Active'] => 1, + $_SESSION['text']['common']['Inactive'] => 0, + ); + + $this->set('statusList', $statusList); + $this->set('info', $info); + $this->set('pageNo', $info['pageno']); + $this->render('searchengine/list', 'ajax'); + } + + # func to change status of search engine + function __changeStatus($seId, $status){ + $seId = intval($seId); + $sql = "update searchengines set status=$status where id=$seId"; + $this->db->query($sql); + } + + # func to delete search engine + function __deleteSearchEngine($seId){ + $seId = intval($seId); + $sql = "delete from searchengines where id=$seId"; + $this->db->query($sql); + + + $sql = "select id from searchresults where searchengine_id=$seId"; + $recordList = $this->db->select($sql); + + if(count($recordList) > 0){ + foreach($recordList as $recordInfo){ + $sql = "delete from searchresultdetails where searchresult_id=".$recordInfo['id']; + $this->db->query($sql); + } + + $sql = "delete from searchresults where searchengine_id=$seId"; + $this->db->query($sql); + } + + } + + # function to check whether captcha found in search engine results + static function isCaptchInSearchResults($searchContent) { + + $captchFound = false; + + // if captcha input field is found + if (stristr($searchContent, 'name="captcha"') || stristr($searchContent, 'id="captcha"')) { + $captchFound = true; + } + + return $captchFound; + } + +} ?> \ No newline at end of file diff --git a/controllers/seoplugins.ctrl.php b/controllers/seoplugins.ctrl.php index 4f9c29ba..55707ea0 100644 --- a/controllers/seoplugins.ctrl.php +++ b/controllers/seoplugins.ctrl.php @@ -1,415 +1,425 @@ -__getSeoPluginInfo($info['pid']); - - $pluginDirName = $pluginInfo['name']; - define('PLUGIN_PATH', SP_PLUGINPATH."/".$pluginDirName); - define('PLUGIN_VIEWPATH', PLUGIN_PATH."/views"); - define('PLUGIN_ID', $info['pid']); - define('PLUGIN_WEBPATH', SP_WEBPATH."/".SP_PLUGINDIR."/".$pluginDirName); - define('PLUGIN_IMGPATH', PLUGIN_WEBPATH."/images"); - define('PLUGIN_CSSPATH', PLUGIN_WEBPATH."/css"); - define('PLUGIN_JSPATH', PLUGIN_WEBPATH."/js"); - define("PLUGIN_SCRIPT_URL", SP_WEBPATH."/seo-plugins.php?pid=".PLUGIN_ID); - - if(file_exists(PLUGIN_PATH."/".SP_PLUGINCONF)){ - include_once(PLUGIN_PATH."/".SP_PLUGINCONF); - } - - include_once(PLUGIN_PATH."/".$pluginDirName.".ctrl.php"); - $pluginControler = New $pluginDirName(); - - // if no action specified just initialize plugin - if ($info['action'] == 'get_plugin_object') { - $pluginControler->initPlugin($data); - return $pluginControler; - } else { - - $this->pluginCtrler = $pluginControler; - $action = empty($info['action']) ? "index" : $info['action']; - $data = ($method=='get') ? $_GET : $_POST; - - // check whethere export report type action - if (empty($data['doc_type']) || ($data['doc_type'] != 'export')) { - $this->loadAllPluginCss(); - $this->loadAllPluginJs(); - } - - $pluginControler->initPlugin($data); - $pluginControler->$action($data); - } - } - - # function to init plugin before do action - function initPlugin($data) { - return; - } - - # func to load plugin css files - function loadAllPluginCss() { - if(file_exists(PLUGIN_PATH."/css")){ - if ($handle = opendir(PLUGIN_PATH."/css")) { - while (false !== ($file = readdir($handle))) { - if ( ($file != ".") && ($file != "..") && preg_match('/\.css$/i', $file) ) { - print ''; - } - } - } - } - } - - # func to load plugin js files - function loadAllPluginJs() { - if(file_exists(PLUGIN_PATH."/js")){ - if ($handle = opendir(PLUGIN_PATH."/js")) { - while (false !== ($file = readdir($handle))) { - if ( ($file != ".") && ($file != "..") && preg_match('/\.js$/i', $file) ) { - print ''; - } - } - } - } - } - - # index function - function showSeoPlugins($info=''){ - $this->layout = "default"; - $sql = "select * from seoplugins where status=1 and installed=1 order by id"; - $menuList = $this->db->select($sql); - if(count($menuList) <= 0){ - $msg = $_SESSION['text']['label']['noactiveplugins']; - $msgButton = ''.$this->spTextPlugin['Download Seo Panel Plugins'].' >>'; - $this->set('msg', $msg); - $this->set('msgButton', $msgButton); - $this->render('common/notfound'); - exit; - } - - # to get sub menus under a plugin main menu - foreach($menuList as $i => $menuInfo){ - @Session::setSession('plugin_id', $menuInfo['id']); - $pluginDirName = $menuInfo['name']; - $menuFile = SP_PLUGINPATH."/".$pluginDirName."/views/".SP_PLUGINMENUFILE; - if(file_exists($menuFile)){ - $menuList[$i]['menu'] = @View::fetchFile($menuFile); - }else{ - $menuList[$i]['menu'] = ""; - } - } - - $this->set('menuList', $menuList); - $menuSelected = empty($info['menu_selected']) ? $menuList[0]['id'] : $info['menu_selected']; - $this->set('menuSelected', $menuSelected); - - $this->render('seoplugins/showseoplugins'); - } - - # func to get all seo tools - function __getAllSeoPlugins(){ - $sql = "select * from seoplugins order by id"; - $seoPluginList = $this->db->select($sql); - return $seoPluginList; - } - - # func to list seo tools - function listSeoPlugins($msg='', $error=false){ - - if(empty($msg)) $this->__updateAllSeoPlugins(); - $userId = isLoggedIn(); - $this->set('msg', $msg); - $this->set('error', $error); - - $sql = "select * from seoplugins order by id"; - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages('seo-plugins-manager.php?'); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - - $seoPluginList = $this->db->select($sql); - $this->set('pageNo', $_GET['pageno']); - $this->set('list', $seoPluginList); - $this->render('seoplugins/listseoplugins'); - } - - #function to change status of seo plugins - function changeStatus($seoPluginId, $status){ - $status = intval($status); - $seoPluginId = intval($seoPluginId); - $sql = "update seoplugins set status=$status where id=$seoPluginId"; - $this->db->query($sql); - } - - #function to change installed status of seo plugins - function __changeInstallStatus($seoPluginId, $status){ - $status = intval($status); - $seoPluginId = intval($seoPluginId); - $sql = "update seoplugins set installed=$status where id=$seoPluginId"; - $this->db->query($sql); - } - - # func to get seo plugin info - function __getSeoPluginInfo($val, $col='id') { - $val = ($col == 'id') ? intval($val) : addslashes($val); - $sql = "select * from seoplugins where $col='$val'"; - $seoPluginInfo = $this->db->select($sql, true); - return $seoPluginInfo; - } - - # func to edit seo plugin - function editSeoPlugin($info, $error=false){ - - if($error){ - $this->set('post', $info); - }else{ - $info['pid'] = intval($info['pid']); - $this->set('post', $this->__getSeoPluginInfo($info['pid'])); - } - - $this->render('seoplugins/editseoplugin'); - } - - # func to list seo plugin info - function listPluginInfo($pluginId){ - $pluginId = intval($pluginId); - $this->set('pluginInfo', $this->__getSeoPluginInfo($pluginId)); - $this->set('pageNo', $_GET['pageno']); - $this->render('seoplugins/listplugininfo'); - } - - function updateSeoPlugin($listInfo){ - - $listInfo['id'] = intval($listInfo['id']); - $this->set('post', $listInfo); - $errMsg['plugin_name'] = formatErrorMsg($this->validate->checkBlank($listInfo['plugin_name'])); - if(!$this->validate->flagErr){ - $sql = "update seoplugins set - label='".addslashes($listInfo['plugin_name'])."' - where id={$listInfo['id']}"; - $this->db->query($sql); - $this->listSeoPlugins(); - }else{ - $this->set('errMsg', $errMsg); - $this->editSeoPlugin($listInfo, true); - } - } - - function updatePluginInfo($pluginId, $pluginInfo){ - - $pluginId = intval($pluginId); - $sql = "update seoplugins set - label='".addslashes($pluginInfo['label'])."', - author='".addslashes($pluginInfo['author'])."', - description='".addslashes($pluginInfo['description'])."', - version='{$pluginInfo['version']}', - website='{$pluginInfo['website']}' - where id=$pluginId"; - $this->db->query($sql); - } - - # func to upgrade seo plugin - function upgradeSeoPlugin($pluginId){ - $pluginInfo = $this->__getSeoPluginInfo($pluginId); - - if(file_exists(SP_PLUGINPATH."/".$pluginInfo['name'])){ - $pluginDBFile = SP_PLUGINPATH."/".$pluginInfo['name']."/".SP_PLUGINUPGRADEFILE; - if(file_exists($pluginDBFile)){ - $this->db->debugMode = false; - $this->db->importDatabaseFile($pluginDBFile, false); - } - - # parse plugin info - $pluginInfo = $this->parsePluginInfoFile($pluginInfo['name']); - $this->updatePluginInfo($pluginId, $pluginInfo); - - $this->__changeInstallStatus($pluginId, 1); - $this->listSeoPlugins("Plugin {$pluginInfo['label']} upgraded successfully!"); - }else{ - $this->__changeInstallStatus($pluginId, 0); - $this->listSeoPlugins("Plugin {$pluginInfo['label']} upgrade failed!", true); - } - } - - # func to re install the seo plugin - function reInstallSeoPlugin($pluginId){ - $pluginInfo = $this->__getSeoPluginInfo($pluginId); - - if(file_exists(SP_PLUGINPATH."/".$pluginInfo['name'])){ - $pluginDBFile = SP_PLUGINPATH."/".$pluginInfo['name']."/".SP_PLUGINDBFILE; - if(file_exists($pluginDBFile)){ - $this->db->debugMode = false; - $this->db->importDatabaseFile($pluginDBFile, false); - } - - # parse plugin info - $pluginInfo = $this->parsePluginInfoFile($pluginInfo['name']); - $this->updatePluginInfo($pluginId, $pluginInfo); - - $this->__changeInstallStatus($pluginId, 1); - $this->listSeoPlugins("Plugin {$pluginInfo['label']} re-installed successfully!"); - }else{ - $this->__changeInstallStatus($pluginId, 0); - $this->listSeoPlugins("Plugin {$pluginInfo['label']} re-installation failed!", true); - } - } - - # to check whether the directory is plugin - function isPluginDirectory($file){ - if ( ($file != ".") && ($file != "..") && ($file != ".svn") && is_dir(SP_PLUGINPATH."/".$file) ) { - if(!preg_match('/^\./', $file)){ - return true; - } - } - return false; - } - - # func to update seo plugins in db - function __updateAllSeoPlugins(){ - $sql = "update seoplugins set installed=0"; - $this->db->query($sql); - - if ($handle = opendir(SP_PLUGINPATH)) { - while (false !== ($file = readdir($handle))) { - if ( $this->isPluginDirectory($file) ) { - $pluginName = $file; - $seoPluginInfo = $this->__getSeoPluginInfo($pluginName, 'name'); - if(empty($seoPluginInfo['id'])){ - - # parse plugin info - $pluginInfo = $this->parsePluginInfoFile($file); - - $sql = "insert into seoplugins(label,name,author,description,version,website,status,installed) - values('".addslashes($pluginInfo['label'])."','$pluginName','".addslashes($pluginInfo['author'])."','".addslashes($pluginInfo['description'])."','{$pluginInfo['version']}','{$pluginInfo['website']}',0,1)"; - $this->db->query($sql); - - $pluginDBFile = SP_PLUGINPATH."/".$file."/".SP_PLUGINDBFILE; - if(file_exists($pluginDBFile)){ - - $this->db->debugMode = false; - $this->db->importDatabaseFile($pluginDBFile, false); - } - - }else{ - $this->__changeInstallStatus($seoPluginInfo['id'], 1); - } - } - } - closedir($handle); - } - } - - # func to parse plugin info file - function parsePluginInfoFile($file) { - $pluginInfo = array(); - $pluginInfoFile = SP_PLUGINPATH."/".$file."/".SP_PLUGININFOFILE; - if(file_exists($pluginInfoFile)){ - $xml = new XMLParser; - $pInfo = $xml->parse($pluginInfoFile); - if(!empty($pInfo[0]['child'])){ - foreach($pInfo[0]['child'] as $info){ - $infoCol = strtolower($info['name']); - $pluginInfo[$infoCol] = $info['content']; - } - } - } - - $pluginInfo['label'] = empty($pluginInfo['label']) ? $file : $pluginInfo['label']; - $pluginInfo['version'] = empty($pluginInfo['version']) ? '1.0.0' : $pluginInfo['version']; - $pluginInfo['author'] = empty($pluginInfo['author']) ? 'Seo Panel': $pluginInfo['author']; - $pluginInfo['website'] = empty($pluginInfo['website']) ? SP_PLUGINSITE : $pluginInfo['website']; - return $pluginInfo; - } - - # function to create helpers for main controlller - function createHelper($helperName) { - - include_once(PLUGIN_PATH."/".strtolower($helperName).".ctrl.php"); - $helperObj = New $helperName(); - return $helperObj; - } - - # func to get plugin language texts - function getPluginLanguageTexts($category, $langCode='en', $table='') { - $langTexts = array(); - - $sql = "select label,content from $table where category='$category' and lang_code='$langCode' and content!='' order by label"; - $textList = $this->db->select($sql); - foreach ($textList as $listInfo) { - $langTexts[$listInfo['label']] = stripslashes($listInfo['content']); - } - - # if langauge is not english - if ($langCode != 'en') { - $defaultTexts = $this->getPluginLanguageTexts($category, 'en', $table); - foreach ($defaultTexts as $label => $content) { - if (empty($langTexts[$label])) { - $langTexts[$label] = $content; - } - } - } - - return $langTexts; - } - - # func to set language texts - function setPluginTextsForRender($category='', $table='') { - - if (empty($this->pluginText)) { - $this->pluginText = $this->getPluginLanguageTexts($category, $_SESSION['lang_code'], $table); - $this->set('pluginText', $this->pluginText); - } - } - - # function to check whether a plugin is installed and active - function isPluginActive($value, $col = 'name') { - $sql = "select * from seoplugins where $col='".addslashes($value)."' and installed=1 and status=1"; - $pluginInfo = $this->db->select($sql, true); - return empty($pluginInfo['id']) ? false : $pluginInfo; - } - - # function to create plugin object - function createPluginObject($pluginName) { - $pluginInfo = $this->__getSeoPluginInfo($pluginName, 'name'); - $info['pid'] = $pluginInfo['id']; - $info['action'] = "get_plugin_object"; - $pluginCtrler = $this->manageSeoPlugins($info); - return $pluginCtrler; - } - -} +__getSeoPluginInfo($info['pid']); + + $pluginDirName = $pluginInfo['name']; + define('PLUGIN_PATH', SP_PLUGINPATH."/".$pluginDirName); + define('PLUGIN_VIEWPATH', PLUGIN_PATH."/views"); + define('PLUGIN_ID', $info['pid']); + define('PLUGIN_WEBPATH', SP_WEBPATH."/".SP_PLUGINDIR."/".$pluginDirName); + define('PLUGIN_IMGPATH', PLUGIN_WEBPATH."/images"); + define('PLUGIN_CSSPATH', PLUGIN_WEBPATH."/css"); + define('PLUGIN_JSPATH', PLUGIN_WEBPATH."/js"); + define("PLUGIN_SCRIPT_URL", SP_WEBPATH."/seo-plugins.php?pid=".PLUGIN_ID); + + if(file_exists(PLUGIN_PATH."/".SP_PLUGINCONF)){ + include_once(PLUGIN_PATH."/".SP_PLUGINCONF); + } + + include_once(PLUGIN_PATH."/".$pluginDirName.".ctrl.php"); + $pluginControler = New $pluginDirName(); + + // if no action specified just initialize plugin + if ($info['action'] == 'get_plugin_object') { + $pluginControler->initPlugin($data); + return $pluginControler; + } else { + + $this->pluginCtrler = $pluginControler; + $action = empty($info['action']) ? "index" : $info['action']; + $data = ($method=='get') ? $_GET : $_POST; + + // check whethere export report type action + if (empty($data['doc_type']) || ($data['doc_type'] != 'export')) { + $this->loadAllPluginCss(); + $this->loadAllPluginJs(); + } + + $pluginControler->initPlugin($data); + $pluginControler->$action($data); + } + } + + # function to init plugin before do action + function initPlugin($data) { + return; + } + + function loadAllPlugins(){ + $plugin_list = $this->__getAllSeoPlugins(); + foreach($plugin_list as $k => $v){ + $pluginDirName = $v['name']; + if(file_exists(SP_PLUGINPATH."/".$pluginDirName."/".SP_PLUGINLOAD)){ + include_once(SP_PLUGINPATH."/".$pluginDirName."/".SP_PLUGINLOAD); + } + } + } + + # func to load plugin css files + function loadAllPluginCss() { + if(file_exists(PLUGIN_PATH."/css")){ + if ($handle = opendir(PLUGIN_PATH."/css")) { + while (false !== ($file = readdir($handle))) { + if ( ($file != ".") && ($file != "..") && preg_match('/\.css$/i', $file) ) { + print ''; + } + } + } + } + } + + # func to load plugin js files + function loadAllPluginJs() { + if(file_exists(PLUGIN_PATH."/js")){ + if ($handle = opendir(PLUGIN_PATH."/js")) { + while (false !== ($file = readdir($handle))) { + if ( ($file != ".") && ($file != "..") && preg_match('/\.js$/i', $file) ) { + print ''; + } + } + } + } + } + + # index function + function showSeoPlugins($info=''){ + $this->layout = "default"; + $sql = "select * from seoplugins where status=1 and installed=1 order by id"; + $menuList = $this->db->select($sql); + if(count($menuList) <= 0){ + $msg = $_SESSION['text']['label']['noactiveplugins']; + $msgButton = ''.$this->spTextPlugin['Download Seo Panel Plugins'].' >>'; + $this->set('msg', $msg); + $this->set('msgButton', $msgButton); + $this->render('common/notfound'); + exit; + } + + # to get sub menus under a plugin main menu + foreach($menuList as $i => $menuInfo){ + @Session::setSession('plugin_id', $menuInfo['id']); + $pluginDirName = $menuInfo['name']; + $menuFile = SP_PLUGINPATH."/".$pluginDirName."/views/".SP_PLUGINMENUFILE; + if(file_exists($menuFile)){ + $menuList[$i]['menu'] = @View::fetchFile($menuFile); + }else{ + $menuList[$i]['menu'] = ""; + } + } + + $this->set('menuList', $menuList); + $menuSelected = empty($info['menu_selected']) ? $menuList[0]['id'] : $info['menu_selected']; + $this->set('menuSelected', $menuSelected); + + $this->render('seoplugins/showseoplugins'); + } + + # func to get all seo tools + function __getAllSeoPlugins(){ + $sql = "select * from seoplugins order by id"; + $seoPluginList = $this->db->select($sql); + return $seoPluginList; + } + + # func to list seo tools + function listSeoPlugins($msg='', $error=false){ + + if(empty($msg)) $this->__updateAllSeoPlugins(); + $userId = isLoggedIn(); + $this->set('msg', $msg); + $this->set('error', $error); + + $sql = "select * from seoplugins order by id"; + + # pagination setup + $this->db->query($sql, true); + $this->paging->setDivClass('pagingdiv'); + $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); + $pagingDiv = $this->paging->printPages('seo-plugins-manager.php?'); + $this->set('pagingDiv', $pagingDiv); + $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; + + $seoPluginList = $this->db->select($sql); + $this->set('pageNo', $_GET['pageno']); + $this->set('list', $seoPluginList); + $this->render('seoplugins/listseoplugins'); + } + + #function to change status of seo plugins + function changeStatus($seoPluginId, $status){ + $status = intval($status); + $seoPluginId = intval($seoPluginId); + $sql = "update seoplugins set status=$status where id=$seoPluginId"; + $this->db->query($sql); + } + + #function to change installed status of seo plugins + function __changeInstallStatus($seoPluginId, $status){ + $status = intval($status); + $seoPluginId = intval($seoPluginId); + $sql = "update seoplugins set installed=$status where id=$seoPluginId"; + $this->db->query($sql); + } + + # func to get seo plugin info + function __getSeoPluginInfo($val, $col='id') { + $val = ($col == 'id') ? intval($val) : addslashes($val); + $sql = "select * from seoplugins where $col='$val'"; + $seoPluginInfo = $this->db->select($sql, true); + return $seoPluginInfo; + } + + # func to edit seo plugin + function editSeoPlugin($info, $error=false){ + + if($error){ + $this->set('post', $info); + }else{ + $info['pid'] = intval($info['pid']); + $this->set('post', $this->__getSeoPluginInfo($info['pid'])); + } + + $this->render('seoplugins/editseoplugin'); + } + + # func to list seo plugin info + function listPluginInfo($pluginId){ + $pluginId = intval($pluginId); + $this->set('pluginInfo', $this->__getSeoPluginInfo($pluginId)); + $this->set('pageNo', $_GET['pageno']); + $this->render('seoplugins/listplugininfo'); + } + + function updateSeoPlugin($listInfo){ + + $listInfo['id'] = intval($listInfo['id']); + $this->set('post', $listInfo); + $errMsg['plugin_name'] = formatErrorMsg($this->validate->checkBlank($listInfo['plugin_name'])); + if(!$this->validate->flagErr){ + $sql = "update seoplugins set + label='".addslashes($listInfo['plugin_name'])."' + where id={$listInfo['id']}"; + $this->db->query($sql); + $this->listSeoPlugins(); + }else{ + $this->set('errMsg', $errMsg); + $this->editSeoPlugin($listInfo, true); + } + } + + function updatePluginInfo($pluginId, $pluginInfo){ + + $pluginId = intval($pluginId); + $sql = "update seoplugins set + label='".addslashes($pluginInfo['label'])."', + author='".addslashes($pluginInfo['author'])."', + description='".addslashes($pluginInfo['description'])."', + version='{$pluginInfo['version']}', + website='{$pluginInfo['website']}' + where id=$pluginId"; + $this->db->query($sql); + } + + # func to upgrade seo plugin + function upgradeSeoPlugin($pluginId){ + $pluginInfo = $this->__getSeoPluginInfo($pluginId); + + if(file_exists(SP_PLUGINPATH."/".$pluginInfo['name'])){ + $pluginDBFile = SP_PLUGINPATH."/".$pluginInfo['name']."/".SP_PLUGINUPGRADEFILE; + if(file_exists($pluginDBFile)){ + $this->db->debugMode = false; + $this->db->importDatabaseFile($pluginDBFile, false); + } + + # parse plugin info + $pluginInfo = $this->parsePluginInfoFile($pluginInfo['name']); + $this->updatePluginInfo($pluginId, $pluginInfo); + + $this->__changeInstallStatus($pluginId, 1); + $this->listSeoPlugins("Plugin {$pluginInfo['label']} upgraded successfully!"); + }else{ + $this->__changeInstallStatus($pluginId, 0); + $this->listSeoPlugins("Plugin {$pluginInfo['label']} upgrade failed!", true); + } + } + + # func to re install the seo plugin + function reInstallSeoPlugin($pluginId){ + $pluginInfo = $this->__getSeoPluginInfo($pluginId); + + if(file_exists(SP_PLUGINPATH."/".$pluginInfo['name'])){ + $pluginDBFile = SP_PLUGINPATH."/".$pluginInfo['name']."/".SP_PLUGINDBFILE; + if(file_exists($pluginDBFile)){ + $this->db->debugMode = false; + $this->db->importDatabaseFile($pluginDBFile, false); + } + + # parse plugin info + $pluginInfo = $this->parsePluginInfoFile($pluginInfo['name']); + $this->updatePluginInfo($pluginId, $pluginInfo); + + $this->__changeInstallStatus($pluginId, 1); + $this->listSeoPlugins("Plugin {$pluginInfo['label']} re-installed successfully!"); + }else{ + $this->__changeInstallStatus($pluginId, 0); + $this->listSeoPlugins("Plugin {$pluginInfo['label']} re-installation failed!", true); + } + } + + # to check whether the directory is plugin + function isPluginDirectory($file){ + if ( ($file != ".") && ($file != "..") && ($file != ".svn") && is_dir(SP_PLUGINPATH."/".$file) ) { + if(!preg_match('/^\./', $file)){ + return true; + } + } + return false; + } + + # func to update seo plugins in db + function __updateAllSeoPlugins(){ + $sql = "update seoplugins set installed=0"; + $this->db->query($sql); + + if ($handle = opendir(SP_PLUGINPATH)) { + while (false !== ($file = readdir($handle))) { + if ( $this->isPluginDirectory($file) ) { + $pluginName = $file; + $seoPluginInfo = $this->__getSeoPluginInfo($pluginName, 'name'); + if(empty($seoPluginInfo['id'])){ + + # parse plugin info + $pluginInfo = $this->parsePluginInfoFile($file); + + $sql = "insert into seoplugins(label,name,author,description,version,website,status,installed) + values('".addslashes($pluginInfo['label'])."','$pluginName','".addslashes($pluginInfo['author'])."','".addslashes($pluginInfo['description'])."','{$pluginInfo['version']}','{$pluginInfo['website']}',0,1)"; + $this->db->query($sql); + + $pluginDBFile = SP_PLUGINPATH."/".$file."/".SP_PLUGINDBFILE; + if(file_exists($pluginDBFile)){ + + $this->db->debugMode = false; + $this->db->importDatabaseFile($pluginDBFile, false); + } + + }else{ + $this->__changeInstallStatus($seoPluginInfo['id'], 1); + } + } + } + closedir($handle); + } + } + + # func to parse plugin info file + function parsePluginInfoFile($file) { + $pluginInfo = array(); + $pluginInfoFile = SP_PLUGINPATH."/".$file."/".SP_PLUGININFOFILE; + if(file_exists($pluginInfoFile)){ + $xml = new XMLParser; + $pInfo = $xml->parse($pluginInfoFile); + if(!empty($pInfo[0]['child'])){ + foreach($pInfo[0]['child'] as $info){ + $infoCol = strtolower($info['name']); + $pluginInfo[$infoCol] = $info['content']; + } + } + } + + $pluginInfo['label'] = empty($pluginInfo['label']) ? $file : $pluginInfo['label']; + $pluginInfo['version'] = empty($pluginInfo['version']) ? '1.0.0' : $pluginInfo['version']; + $pluginInfo['author'] = empty($pluginInfo['author']) ? 'Seo Panel': $pluginInfo['author']; + $pluginInfo['website'] = empty($pluginInfo['website']) ? SP_PLUGINSITE : $pluginInfo['website']; + return $pluginInfo; + } + + # function to create helpers for main controlller + function createHelper($helperName) { + + include_once(PLUGIN_PATH."/".strtolower($helperName).".ctrl.php"); + $helperObj = New $helperName(); + return $helperObj; + } + + # func to get plugin language texts + function getPluginLanguageTexts($category, $langCode='en', $table='') { + $langTexts = array(); + + $sql = "select label,content from $table where category='$category' and lang_code='$langCode' and content!='' order by label"; + $textList = $this->db->select($sql); + foreach ($textList as $listInfo) { + $langTexts[$listInfo['label']] = stripslashes($listInfo['content']); + } + + # if langauge is not english + if ($langCode != 'en') { + $defaultTexts = $this->getPluginLanguageTexts($category, 'en', $table); + foreach ($defaultTexts as $label => $content) { + if (empty($langTexts[$label])) { + $langTexts[$label] = $content; + } + } + } + + return $langTexts; + } + + # func to set language texts + function setPluginTextsForRender($category='', $table='') { + + if (empty($this->pluginText)) { + $this->pluginText = $this->getPluginLanguageTexts($category, $_SESSION['lang_code'], $table); + $this->set('pluginText', $this->pluginText); + } + } + + # function to check whether a plugin is installed and active + function isPluginActive($value, $col = 'name') { + $sql = "select * from seoplugins where $col='".addslashes($value)."' and installed=1 and status=1"; + $pluginInfo = $this->db->select($sql, true); + return empty($pluginInfo['id']) ? false : $pluginInfo; + } + + # function to create plugin object + function createPluginObject($pluginName) { + $pluginInfo = $this->__getSeoPluginInfo($pluginName, 'name'); + $info['pid'] = $pluginInfo['id']; + $info['action'] = "get_plugin_object"; + $pluginCtrler = $this->manageSeoPlugins($info); + return $pluginCtrler; + } + +} ?> \ No newline at end of file diff --git a/controllers/seotools.ctrl.php b/controllers/seotools.ctrl.php index 635bd64c..c38146ec 100644 --- a/controllers/seotools.ctrl.php +++ b/controllers/seotools.ctrl.php @@ -1,118 +1,118 @@ -layout = "default"; - if(isAdmin()){ - $sql = "select * from seotools where status=1"; - }else{ - $sql = "select * from seotools where status=1 and user_access=1"; - } - $sql .= " order by id"; - - $menuList = $this->db->select($sql); - if(count($menuList) <= 0){ - $this->set('msg', $_SESSION['text']['common']['noactivetools']); - $this->render('common/notfound'); - exit; - } - - $this->set('menuList', $menuList); - $defaultArgs = empty($info['default_args']) ? "" : urldecode($info['default_args']); - switch($info['menu_sec']){ - - case "sitemap-generator": - $defaultScript = "sitemap.php"; - break; - - case "site-auditor": - $defaultScript = "siteauditor.php"; - break; - - case "rank-checker": - $defaultScript = "rank.php"; - break; - - case "backlink-checker": - $defaultScript = "backlinks.php"; - break; - - case "directory-submission": - $defaultScript = "directories.php"; - break; - - case "saturation-checker": - $defaultScript = "saturationchecker.php"; - break; - - default: - $seoToolInfo = $this->__getSeoToolInfo('keyword-position-checker', 'url_section'); - if($seoToolInfo['status'] == 1){ - $info['menu_sec'] = 'keyword-position-checker'; - $defaultScript = "reports.php"; - $defaultArgs = empty($defaultArgs) ? "sec=reportsum" : $defaultArgs; - } - } - - $this->set('menuSelected', $info['menu_sec']); - $this->set('defaultScript', $defaultScript); - $this->set('defaultArgs', $defaultArgs); - $this->render('seotools/index'); - } - - # func to get all seo tools - function __getAllSeoTools(){ - $sql = "select * from seotools order by id"; - $seoToolList = $this->db->select($sql); - return $seoToolList; - } - - # func to get seo tool info - function __getSeoToolInfo($val, $col='id'){ - $sql = "select * from seotools where $col='$val'"; - $seoToolInfo = $this->db->select($sql, true); - return $seoToolInfo; - } - - # func to list seo tools - function listSeoTools(){ - - $userId = isLoggedIn(); - $seoToolList = $this->__getAllSeoTools(); - $this->set('list', $seoToolList); - $this->render('seotools/listseotools'); - } - - #function to change status of seo tools - function changeStatus($seoToolId, $status, $col='status'){ - - $seoToolId = intval($seoToolId); - $sql = "update seotools set $col=$status where id=$seoToolId"; - $this->db->query($sql); - } -} +layout = "default"; + if(isAdmin()){ + $sql = "select * from seotools where status=1"; + }else{ + $sql = "select * from seotools where status=1 and user_access=1"; + } + $sql .= " order by id"; + + $menuList = $this->db->select($sql); + if(count($menuList) <= 0){ + $this->set('msg', $_SESSION['text']['common']['noactivetools']); + $this->render('common/notfound'); + exit; + } + + $this->set('menuList', $menuList); + $defaultArgs = empty($info['default_args']) ? "" : urldecode($info['default_args']); + switch($info['menu_sec']){ + + case "sitemap-generator": + $defaultScript = "sitemap.php"; + break; + + case "site-auditor": + $defaultScript = "siteauditor.php"; + break; + + case "rank-checker": + $defaultScript = "rank.php"; + break; + + case "backlink-checker": + $defaultScript = "backlinks.php"; + break; + + case "directory-submission": + $defaultScript = "directories.php"; + break; + + case "saturation-checker": + $defaultScript = "saturationchecker.php"; + break; + + default: + $seoToolInfo = $this->__getSeoToolInfo('keyword-position-checker', 'url_section'); + if($seoToolInfo['status'] == 1){ + $info['menu_sec'] = 'keyword-position-checker'; + $defaultScript = "reports.php"; + $defaultArgs = empty($defaultArgs) ? "sec=reportsum" : $defaultArgs; + } + } + + $this->set('menuSelected', $info['menu_sec']); + $this->set('defaultScript', $defaultScript); + $this->set('defaultArgs', $defaultArgs); + $this->render('seotools/index'); + } + + # func to get all seo tools + function __getAllSeoTools(){ + $sql = "select * from seotools order by id"; + $seoToolList = $this->db->select($sql); + return $seoToolList; + } + + # func to get seo tool info + function __getSeoToolInfo($val, $col='id'){ + $sql = "select * from seotools where $col='$val'"; + $seoToolInfo = $this->db->select($sql, true); + return $seoToolInfo; + } + + # func to list seo tools + function listSeoTools(){ + + $userId = isLoggedIn(); + $seoToolList = $this->__getAllSeoTools(); + $this->set('list', $seoToolList); + $this->render('seotools/listseotools'); + } + + #function to change status of seo tools + function changeStatus($seoToolId, $status, $col='status'){ + + $seoToolId = intval($seoToolId); + $sql = "update seotools set $col=$status where id=$seoToolId"; + $this->db->query($sql); + } +} ?> \ No newline at end of file diff --git a/controllers/settings.ctrl.php b/controllers/settings.ctrl.php index 9c71f376..b4559f53 100644 --- a/controllers/settings.ctrl.php +++ b/controllers/settings.ctrl.php @@ -1,171 +1,171 @@ -set('list', $this->__getAllSettings(true, 1, $category)); - - if ($category == 'system') { - $langCtrler = New LanguageController(); - $langList = $langCtrler->__getAllLanguages(" where translated=1"); - $this->set('langList', $langList); - - $timezoneCtrler = New TimeZoneController(); - $timezoneList = $timezoneCtrler->__getAllTimezones(); - $this->set('timezoneList', $timezoneList); - - $currencyCtrler = new CurrencyController(); - $this->set('currencyList', $currencyCtrler->__getAllCurrency(" and paypal=1 and status=1 and name!=''")); - - } - - $this->set('category', $category); - - // if report settings page - if ($category == 'report') { - - $spTextReport = $this->getLanguageTexts('report', $_SESSION['lang_code']); - $this->set('spTextReport', $spTextReport); - $scheduleList = array( - 1 => $_SESSION['text']['label']['Daily'], - 2 => $spTextReport['2 Days'], - 7 => $_SESSION['text']['label']['Weekly'], - 30 => $_SESSION['text']['label']['Monthly'], - ); - $this->set('scheduleList', $scheduleList); - $this->render('settings/showreportsettings'); - - } else if ($category == 'proxy') { - - $spTextProxy = $this->getLanguageTexts('proxy', $_SESSION['lang_code']); - $this->set('spTextProxy', $spTextProxy); - $this->render('settings/showproxysettings'); - } else { - - $spTextPanel = $this->getLanguageTexts('panel', $_SESSION['lang_code']); - - // switch through category - switch ($category) { - - case "api": - $this->set('headLabel', $spTextPanel['API Settings']); - break; - - case "moz": - $this->set('headLabel', $spTextPanel['MOZ Settings']); - break; - - default: - break; - - } - - $this->render('settings/showsettings'); - } - } - - function updateSystemSettings($postInfo) { - - $setList = $this->__getAllSettings(true, 1, $postInfo['category']); - foreach($setList as $setInfo){ - - switch($setInfo['set_name']){ - - case "SP_PAGINGNO": - $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); - $postInfo[$setInfo['set_name']] = empty($postInfo[$setInfo['set_name']]) ? SP_PAGINGNO_DEFAULT : $postInfo[$setInfo['set_name']]; - break; - - case "SP_CRAWL_DELAY": - case "SP_USER_GEN_REPORT": - case "SA_CRAWL_DELAY_TIME": - case "SA_MAX_NO_PAGES": - case "SP_NUMBER_KEYWORDS_CRON": - $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); - break; - - case "SP_SMTP_HOST": - case "SP_SMTP_USERNAME": - case "SP_SMTP_PASSWORD": - // if smtp mail enabled then check all smtp details entered - if (empty($postInfo[$setInfo['set_name']]) && !empty($postInfo['SP_SMTP_MAIL'])) { - $this->set('errorMsg', $this->spTextSettings['entersmtpdetails']); - $this->showSystemSettings($postInfo['category']); - exit; - } - break; - - case "SP_SYSTEM_REPORT_INTERVAL": - // update users report schedule if system report schedule is greater than them - $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); - $sql = "Update reports_settings set report_interval=".$postInfo[$setInfo['set_name']]." where report_interval<".$postInfo[$setInfo['set_name']]; - $userList = $this->db->query($sql); - break; - } - - $sql = "update settings set set_val='".addslashes($postInfo[$setInfo['set_name']])."' where set_name='".addslashes($setInfo['set_name'])."'"; - $this->db->query($sql); - } - - $this->set('saved', 1); - $this->showSystemSettings($postInfo['category']); - } - - # func to show about us of seo panel - function showAboutUs() { - - $sql = "select t.*,l.lang_name from translators t,languages l where t.lang_code=l.lang_code"; - $transList = $this->db->select($sql); - $this->set('transList', $transList); - - include_once(SP_CTRLPATH."/information.ctrl.php"); - $infoCtrler = new InformationController(); - $this->set('sponsors', $infoCtrler->getSponsors()); - $this->render('settings/aboutus'); - } - - # func to show version of seo panel - function showVersion() { - $this->render('settings/version'); - } - - # function to check version - function checkVersion() { - $content = $this->spider->getContent(SP_VERSION_PAGE); - $content['page'] = str_replace('Version:', '', $content['page']); - $latestVersion = str_replace('.', '', $content['page']); - $installVersion = str_replace('.', '', SP_INSTALLED); - if ($latestVersion > $installVersion) { - echo showErrorMsg($this->spTextSettings['versionnotuptodatemsg']."({$content['page']}) from ".SP_DOWNLOAD_LINK."", false); - } else { - echo showSuccessMsg($this->spTextSettings["Your Seo Panel installation is up to date"], false); - } - } - -} +set('list', $this->__getAllSettings(true, 1, $category)); + + if ($category == 'system') { + $langCtrler = New LanguageController(); + $langList = $langCtrler->__getAllLanguages(" where translated=1"); + $this->set('langList', $langList); + + $timezoneCtrler = New TimeZoneController(); + $timezoneList = $timezoneCtrler->__getAllTimezones(); + $this->set('timezoneList', $timezoneList); + + $currencyCtrler = new CurrencyController(); + $this->set('currencyList', $currencyCtrler->__getAllCurrency(" and paypal=1 and status=1 and name!=''")); + + } + + $this->set('category', $category); + + // if report settings page + if ($category == 'report') { + + $spTextReport = $this->getLanguageTexts('report', $_SESSION['lang_code']); + $this->set('spTextReport', $spTextReport); + $scheduleList = array( + 1 => $_SESSION['text']['label']['Daily'], + 2 => $spTextReport['2 Days'], + 7 => $_SESSION['text']['label']['Weekly'], + 30 => $_SESSION['text']['label']['Monthly'], + ); + $this->set('scheduleList', $scheduleList); + $this->render('settings/showreportsettings'); + + } else if ($category == 'proxy') { + + $spTextProxy = $this->getLanguageTexts('proxy', $_SESSION['lang_code']); + $this->set('spTextProxy', $spTextProxy); + $this->render('settings/showproxysettings'); + } else { + + $spTextPanel = $this->getLanguageTexts('panel', $_SESSION['lang_code']); + + // switch through category + switch ($category) { + + case "api": + $this->set('headLabel', $spTextPanel['API Settings']); + break; + + case "moz": + $this->set('headLabel', $spTextPanel['MOZ Settings']); + break; + + default: + break; + + } + + $this->render('settings/showsettings'); + } + } + + function updateSystemSettings($postInfo) { + + $setList = $this->__getAllSettings(true, 1, $postInfo['category']); + foreach($setList as $setInfo){ + + switch($setInfo['set_name']){ + + case "SP_PAGINGNO": + $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); + $postInfo[$setInfo['set_name']] = empty($postInfo[$setInfo['set_name']]) ? SP_PAGINGNO_DEFAULT : $postInfo[$setInfo['set_name']]; + break; + + case "SP_CRAWL_DELAY": + case "SP_USER_GEN_REPORT": + case "SA_CRAWL_DELAY_TIME": + case "SA_MAX_NO_PAGES": + case "SP_NUMBER_KEYWORDS_CRON": + $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); + break; + + case "SP_SMTP_HOST": + case "SP_SMTP_USERNAME": + case "SP_SMTP_PASSWORD": + // if smtp mail enabled then check all smtp details entered + if (empty($postInfo[$setInfo['set_name']]) && !empty($postInfo['SP_SMTP_MAIL'])) { + $this->set('errorMsg', $this->spTextSettings['entersmtpdetails']); + $this->showSystemSettings($postInfo['category']); + exit; + } + break; + + case "SP_SYSTEM_REPORT_INTERVAL": + // update users report schedule if system report schedule is greater than them + $postInfo[$setInfo['set_name']] = intval($postInfo[$setInfo['set_name']]); + $sql = "Update reports_settings set report_interval=".$postInfo[$setInfo['set_name']]." where report_interval<".$postInfo[$setInfo['set_name']]; + $userList = $this->db->query($sql); + break; + } + + $sql = "update settings set set_val='".addslashes($postInfo[$setInfo['set_name']])."' where set_name='".addslashes($setInfo['set_name'])."'"; + $this->db->query($sql); + } + + $this->set('saved', 1); + $this->showSystemSettings($postInfo['category']); + } + + # func to show about us of seo panel + function showAboutUs() { + + $sql = "select t.*,l.lang_name from translators t,languages l where t.lang_code=l.lang_code"; + $transList = $this->db->select($sql); + $this->set('transList', $transList); + + include_once(SP_CTRLPATH."/information.ctrl.php"); + $infoCtrler = new InformationController(); + $this->set('sponsors', $infoCtrler->getSponsors()); + $this->render('settings/aboutus'); + } + + # func to show version of seo panel + function showVersion() { + $this->render('settings/version'); + } + + # function to check version + function checkVersion() { + $content = $this->spider->getContent(SP_VERSION_PAGE); + $content['page'] = str_replace('Version:', '', $content['page']); + $latestVersion = str_replace('.', '', $content['page']); + $installVersion = str_replace('.', '', SP_INSTALLED); + if ($latestVersion > $installVersion) { + echo showErrorMsg($this->spTextSettings['versionnotuptodatemsg']."({$content['page']}) from ".SP_DOWNLOAD_LINK."", false); + } else { + echo showSuccessMsg($this->spTextSettings["Your Seo Panel installation is up to date"], false); + } + } + +} ?> \ No newline at end of file diff --git a/controllers/siteauditor.ctrl.php b/controllers/siteauditor.ctrl.php index cf645852..f6393203 100644 --- a/controllers/siteauditor.ctrl.php +++ b/controllers/siteauditor.ctrl.php @@ -1,919 +1,919 @@ -set('isAdmin', 1); - - $userCtrler = New UserController(); - $userList = $userCtrler->__getAllUsers(); - $this->set('userList', $userList); - - }else{ - $sql = "select w.name,ap.* from websites w, auditorprojects ap where ap.website_id=w.id and user_id=$userId order by ap.id"; - } - $this->set('userId', empty($info['userid']) ? 0 : $info['userid']); - - # pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages('siteauditor.php?userid='.$info['userid']); - $this->set('pagingDiv', $pagingDiv); - $sql .= " limit ".$this->paging->start .",". $this->paging->per_page; - - $projectList = $this->db->select($sql); - foreach ($projectList as $i => $projectInfo) { - $projectList[$i]['total_links'] = $this->getCountcrawledLinks($projectInfo['id']); - $projectList[$i]['crawled_links'] = $this->getCountcrawledLinks($projectInfo['id'], true); - $projectList[$i]['last_updated'] = $this->getProjectLastUpdate($projectInfo['id']); - } - $this->set('pageNo', $info['pageno']); - $this->set('list', $projectList); - $this->render('siteauditor/list'); - } - - // func to create new project - function newProject($info=''){ - - $userId = isLoggedIn(); - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty($info['website_id']) ? $websiteList[0]['id'] : intval($info['website_id']); - $this->set('websiteId', $websiteId); - - if (!isset($info['website_id'])) { - $info['max_links'] = SA_MAX_NO_PAGES; - $info['cron'] = 1; - $this->set('post', $info); - } - - $this->render('siteauditor/new'); - } - - // func to create project - function createProject($listInfo){ - - $userId = isLoggedIn(); - $this->set('post', $listInfo); - $listInfo['website_id'] = intval($listInfo['website_id']); - $listInfo['max_links'] = intval($listInfo['max_links']); - - $errMsg['website_id'] = formatErrorMsg($this->validate->checkBlank($listInfo['website_id'])); - $errMsg['max_links'] = formatErrorMsg($this->validate->checkNumber($listInfo['max_links'])); - if(!$this->validate->flagErr){ - $errorFlag = 0; - if ($listInfo['max_links'] > SA_MAX_NO_PAGES) { - $errorFlag = 1; - $errMsg['max_links'] = formatErrorMsg($this->spTextSA["Number of pages is greater than"]. " ". SA_MAX_NO_PAGES); - } - - if ($listInfo['max_links'] <= 0) { - $errorFlag = 1; - $errMsg['max_links'] = formatErrorMsg($this->spTextSA["Number of pages should be greater than"]. " 0"); - } - - $webCtrler = New WebsiteController(); - $websiteInfo = $webCtrler->__getWebsiteInfo($listInfo['website_id']); - - // commented to exclude site auditor with query arguments also by with out adding fulll url - /*$excludeInfo = $this->checkExcludeLinks($listInfo['exclude_links'], $websiteInfo['url']); - if (!empty($excludeInfo['err_msg'])) { - $errorFlag = 1; - $errMsg['exclude_links'] = formatErrorMsg($excludeInfo['err_msg']); - } - $listInfo['exclude_links'] = $excludeInfo['exclude_links'];*/ - - if (!$errorFlag) { - if (!$this->isProjectExists($listInfo['website_id'])) { - $sql = "insert into auditorprojects(website_id,max_links,exclude_links,check_pr,check_backlinks,check_indexed,store_links_in_page,check_brocken,cron) - values({$listInfo['website_id']},{$listInfo['max_links']},'".addslashes($listInfo['exclude_links'])."', - ".intval($listInfo['check_pr']).",".intval($listInfo['check_backlinks']).",".intval($listInfo['check_indexed']).", - ".intval($listInfo['store_links_in_page']).",".intval($listInfo['check_brocken']).",".intval($listInfo['cron']).")"; - $this->db->query($sql); - $this->showAuditorProjects(); - exit; - }else{ - $errMsg['website_id'] = formatErrorMsg($this->spTextSA['projectalreadyexist']); - } - } - } - $this->set('errMsg', $errMsg); - $this->newProject($listInfo); - } - - // check entered excluded list - function checkExcludeLinks($excludeLinks, $websiteUrl, $exclude=true) { - $linkList = explode(',', $excludeLinks); - $newList = array(); - $errMsg = ""; - $checkUrl = formatUrl($websiteUrl); - foreach ($linkList as $link) { - $link = str_replace(' ', '+', trim($link)); - $linkUrl = formatUrl($link); - if (!empty($linkUrl)) { - $newList[] = $link; - if (empty($errMsg)) { - if (!preg_match("/^".preg_quote($checkUrl, '/')."/", $linkUrl)) { - $linkLabel = $exclude ? $_SESSION['text']['label']["Exclude"] : $_SESSION['text']['label']["Include"]; - $errMsg = "$linkLabel link '$link' {$this->spTextSA['should start with']} '$websiteUrl'"; - } - } - } - } - $excludeLinks = implode(',', $newList); - $retInfo['exclude_links'] = $excludeLinks; - $retInfo['err_msg'] = $errMsg; - return $retInfo; - } - - // function check project already exists - function isProjectExists($websiteId, $projectId=false){ - $sql = "select id from auditorprojects where website_id=$websiteId"; - $sql .= $projectId ? " and id!=$projectId" : ""; - $listInfo = $this->db->select($sql, true); - return empty($listInfo['id']) ? false : $listInfo['id']; - } - - // func to get project info - function __getProjectInfo($projectId) { - $sql = "select p.*,w.url,w.name from auditorprojects p,websites w where p.website_id=w.id and p.id=$projectId"; - $info = $this->db->select($sql, true); - $info['url'] = @Spider::removeTrailingSlash($info['url']); - return $info; - } - - // func to edit project - function editProject($projectId, $listInfo=''){ - $userId = isLoggedIn(); - $projectId = intval($projectId); - if(!empty($projectId)){ - if(empty($listInfo)){ - $listInfo = $this->__getProjectInfo($projectId); - $listInfo['oldName'] = $listInfo['keyword']; - } - $this->set('post', $listInfo); - - $websiteController = New WebsiteController(); - $websiteList = $websiteController->__getAllWebsites($userId, true); - $this->set('websiteList', $websiteList); - $websiteId = empty($listInfo['website_id']) ? $websiteList[0]['id'] : intval($listInfo['website_id']); - $this->set('websiteId', $websiteId); - - $langController = New LanguageController(); - $this->set('langList', $langController->__getAllLanguages()); - $this->render('siteauditor/edit'); - exit; - } - } - - // func to update project - function updateProject($listInfo){ - - $userId = isLoggedIn(); - $listInfo['website_id'] = intval($listInfo['website_id']); - $listInfo['max_links'] = intval($listInfo['max_links']); - $this->set('post', $listInfo); - $errMsg['website_id'] = formatErrorMsg($this->validate->checkBlank($listInfo['website_id'])); - $errMsg['max_links'] = formatErrorMsg($this->validate->checkNumber($listInfo['max_links'])); - if(!$this->validate->flagErr){ - $errorFlag = 0; - if ($listInfo['max_links'] > SA_MAX_NO_PAGES) { - $errorFlag = 1; - $errMsg['max_links'] = formatErrorMsg($this->spTextSA["Number of pages is greater than"]. " ". SA_MAX_NO_PAGES); - } - - if ($listInfo['max_links'] <= 0) { - $errorFlag = 1; - $errMsg['max_links'] = formatErrorMsg($this->spTextSA["Number of pages should be greater than"]. " 0"); - } - - $webCtrler = New WebsiteController(); - $websiteInfo = $webCtrler->__getWebsiteInfo($listInfo['website_id']); - - // commented to exclude site auditor with query arguments also by with out adding fulll url - /*$excludeInfo = $this->checkExcludeLinks($listInfo['exclude_links'], $websiteInfo['url']); - if (!empty($excludeInfo['err_msg'])) { - $errorFlag = 1; - $errMsg['exclude_links'] = formatErrorMsg($excludeInfo['err_msg']); - } - $listInfo['exclude_links'] = $excludeInfo['exclude_links'];*/ - - if (!$errorFlag) { - if (!$this->isProjectExists($listInfo['website_id'], $listInfo['id'])) { - $sql = "Update auditorprojects set - website_id={$listInfo['website_id']}, - max_links={$listInfo['max_links']}, - check_pr=".intval($listInfo['check_pr']).", - check_backlinks=".intval($listInfo['check_backlinks']).", - check_indexed=".intval($listInfo['check_indexed']).", - store_links_in_page=".intval($listInfo['store_links_in_page']).", - check_brocken='".intval($listInfo['check_brocken'])."', - cron='".intval($listInfo['cron'])."', - exclude_links='".addslashes($listInfo['exclude_links'])."' - where id=".$listInfo['id']; - $this->db->query($sql); - $this->showAuditorProjects(); - exit; - }else{ - $errMsg['website_id'] = formatErrorMsg($this->spTextSA['projectalreadyexist']); - } - } - } - $this->set('errMsg', $errMsg); - $this->editProject($listInfo['id'], $listInfo); - } - - // func to change status - function __changeStatus($projectId, $status){ - $projectId = intval($projectId); - $sql = "update auditorprojects set status=$status where id=$projectId"; - $this->db->query($sql); - } - - // func to delete project - function __deleteProject($projectId){ - // delete teh project - $projectId = intval($projectId); - $sql = "delete from auditorprojects where id=$projectId"; - $this->db->query($sql); - - // delete all pages found in reports - $sql = "select id from auditorreports where project_id=$projectId"; - $repList = $this->db->select($sql); - foreach ($repList as $repInfo) { - $this->__deleteReportPage($repInfo['id']); - } - } - - // function to get number of links of a project - function getCountcrawledLinks($projectId, $statusCheck=false, $statusVal=1, $conditions='') { - $sql = "select count(*) count from auditorreports r where r.project_id=$projectId"; - $sql .= $statusCheck ? " and crawled=$statusVal" : ""; - $sql .= $conditions; - $info = $this->db->select($sql, true); - return $info['count'] ? $info['count'] : 0; - } - - // function to get all projects of user - function getAllProjects($where='') { - $sql = "select ap.*,w.url,w.name from auditorprojects ap,websites w where w.id=ap.website_id and w.status=1 and ap.status=1 $where"; - $projectList = $this->db->select($sql); - return $projectList; - } - - // function to get number of links of a project - function getProjectLastUpdate($projectId) { - $sql = "select max(updated) updated from auditorreports r where r.project_id=$projectId"; - $info = $this->db->select($sql, true); - return empty($info['updated']) ? "Not Started" : $info['updated']; - } - - // function to show interface to run a project - function showRunProject($projectId) { - $projectId = intval($projectId); - $projectInfo = $this->__getProjectInfo($projectId); - $projectInfo['total_links'] = $this->getCountcrawledLinks($projectInfo['id']); - $projectInfo['crawled_links'] = $this->getCountcrawledLinks($projectInfo['id'], true); - $projectInfo['last_updated'] = $this->getProjectLastUpdate($projectInfo['id']); - $projectInfo['crawling_url'] = $this->getProjectRandomUrl($projectId); - $this->set('projectInfo', $projectInfo); - $this->render('siteauditor/showrunproject'); - } - - // fucntion to load reports page after teh actions - function loadReportsPage($info='') { - print ""; - } - - // function to check page score - function checkPageScore($info='') { - if (!empty($info['report_id'])) { - $reportId = intval($info['report_id']); - $auditorComp = $this->createComponent('AuditorComponent'); - $reportInfo = $auditorComp->getReportInfo(" and id=$reportId"); - $projectInfo = $this->__getProjectInfo($reportInfo['project_id']); - $auditorComp->runReport($reportInfo['page_url'], $projectInfo, $this->getCountcrawledLinks($projectInfo['id'])); - $this->loadReportsPage($info); - } - } - - // func to delete page of report - function __deleteReportPage($reportId){ - if (!empty($reportId)) { - $reportId = intval($reportId); - - // delete report page - $sql = "delete from auditorreports where id=$reportId"; - $this->db->query($sql); - - // delete all links under this page - $sql = "delete from auditorpagelinks where report_id=$reportId"; - $this->db->query($sql); - } - } - - // function to recheck report pages of project - function recheckReportPages($projectId) { - $projectId = intval($projectId); - if (!empty($projectId)) { - $sql = "update auditorreports set crawled=0 where project_id=$projectId"; - $this->db->query($sql); - - - // delete all pages found in reports - $sql = "select id from auditorreports where project_id=$projectId"; - $repList = $this->db->select($sql); - foreach ($repList as $repInfo) { - // delete all links under this page - $sql = "delete from auditorpagelinks where report_id=".$repInfo['id']; - $this->db->query($sql); - } - - - } - } - - // function to run project, save blog links to database - function runProject($projectId) { - $projectId = intval($projectId); - $projectInfo = $this->__getProjectInfo($projectId); - $completed = 0; - $errorMsg = ''; - if ($reportUrl = $this->getProjectRandomUrl($projectId)) { - $auditorComp = $this->createComponent('AuditorComponent'); - $auditorComp->runReport($reportUrl, $projectInfo, $this->getCountcrawledLinks($projectId)); - $this->set('crawledUrl', $reportUrl); - if (!$crawlUrl = $this->getProjectRandomUrl($projectId)) { - $completed = 1; - } else { - if (!$this->cron) updateJsLocation('crawling_url', $reportUrl); - } - } else { - $completed = 1; - } - - // if execution not through cron - if (!$this->cron) { - updateJsLocation('last_updated', date('Y-m-d H:i:s')); - updateJsLocation('total_links', $this->getCountcrawledLinks($projectId)); - updateJsLocation('crawled_pages', $this->getCountcrawledLinks($projectId, true)); - $this->set('completed', $completed); - $this->set('projectId', $projectId); - $this->set('errorMsg', $errorMsg); - $this->set('projectInfo', $projectInfo); - $this->render('siteauditor/runproject'); - } else { - return $reportUrl; - } - } - - // function to get random url of a project - function getProjectRandomUrl($projectId) { - $sql = "SELECT page_url FROM auditorreports where project_id=$projectId and crawled=0 ORDER BY RAND() LIMIT 1"; - $listInfo = $this->db->select($sql, true); - if (empty($listInfo['page_url'])) { - $totalLinks = $this->getCountcrawledLinks($projectId); - if ($totalLinks == 0) { - $auditorComp = $this->createComponent('AuditorComponent'); - $projectInfo = $this->__getProjectInfo($projectId); - $reportInfo['page_url'] = Spider::formatUrl($projectInfo['url']); - $reportInfo['project_id'] = $projectId; - $auditorComp->saveReportInfo($reportInfo); - return $reportInfo['page_url']; - } else { - return false; - } - } else { - return $listInfo['page_url']; - } - } - - // function to view the reports - function viewReports($info='') { - - $userId = isLoggedIn(); - $where = isAdmin() ? "" : " and w.user_id=$userId"; - $pList = $this->getAllProjects($where); - $projectList = array(); - foreach($pList as $pInfo) { - $pInfo['total_links'] = $this->getCountcrawledLinks($pInfo['id']); - if ($pInfo['total_links'] > 0) { - $projectList[] = $pInfo; - } - } - - if (empty($info['project_id'])) { - $projectId = $projectList[0]['id']; - } else { - $projectId = intval($info['project_id']); - } - $this->set('projectId', $projectId); - $this->set('projectList', $projectList); - - - $reportTypes = array( - 'rp_links' => $this->spTextSA["Link Reports"], - 'rp_summary' => $this->spTextSA["Report Summary"], - 'page_title' => $this->spTextSA["Duplicate Title"], - 'page_description' => $this->spTextSA["Duplicate Description"], - 'page_keywords' => $this->spTextSA["Duplicate Keywords"], - ); - $this->set('reportTypes', $reportTypes); - $this->set('repType', empty($info['report_type']) ? "rp_links" : $info['report_type']); - - $this->render('siteauditor/viewreports'); - } - - //function to show the reports by using view reportss filters - function showProjectReport($data='') { - $data['project_id'] = intval($data['project_id']); - $projectInfo = $this->__getProjectInfo($data['project_id']); - $projectInfo['last_updated'] = $this->getProjectLastUpdate($data['project_id']); - $this->set('projectId', $data['project_id']); - $this->set('projectInfo', $projectInfo); - - $exportVersion = false; - switch($data['doc_type']){ - - case "export": - $exportVersion = true; - break; - - case "pdf": - $this->set('pdfVersion', true); - break; - - case "print": - $this->set('printVersion', true); - break; - } - - switch($data['report_type']) { - - case "rp_summary": - $this->showReportSummary($data, $exportVersion, $projectInfo); - break; - - case "page_title": - case "page_description": - case "page_keywords": - $this->showDuplicateMetaInfo($data, $exportVersion, $projectInfo); - break; - - case "rp_links": - default: - $this->showLinksReport($data, $exportVersion, $projectInfo); - break; - - } - } - - // function to show links reports of a auditor project - function showLinksReport($data, $exportVersion, $projectInfo) { - - $projectId = intval($data['project_id']); - $sql = "select * from auditorreports where project_id=$projectId"; - $filter = ""; - - // check for page rank - if(isset($data['pagerank']) && ($data['pagerank'] != -1)) { - $prMax = intval($data['pagerank']) + 0.5; - $prMin = intval($data['pagerank']) - 0.5; - $sql .= " and pagerank<$prMax and pagerank>=$prMin"; - $filter .= "&pagerank=".$data['pagerank']; - } - - // check for page url - if(!empty($data['page_url'])) { - $pageLink = urldecode($data['page_url']); - $filter .= "&page_url=".urlencode($pageLink); - $sql .= " and page_url like '%".addslashes($pageLink)."%'"; - } - - // check for page url - if(isset($data['crawled']) && ($data['crawled'] != -1) ) { - $data['crawled'] = intval($data['crawled']); - $filter .= "&crawled=".$data['crawled']; - $sql .= " and crawled=".$data['crawled']; - } - - // to find order col - if (!empty($data['order_col'])) { - $orderCol = $data['order_col']; - $orderVal = $data['order_val']; - } else { - $orderCol = 'score'; - $orderVal = 'DESC'; - } - $filter .= "&order_col=$orderCol&order_val=$orderVal"; - $this->set('orderCol', $orderCol); - $this->set('orderVal', $orderVal); - - $pgScriptPath = "siteauditor.php?sec=showreport&report_type=rp_links&project_id=$projectId".$filter; - $this->set('filter', $filter); - - // pagination setup - $this->db->query($sql, true); - $this->paging->setDivClass('pagingdiv'); - $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO); - $pagingDiv = $this->paging->printPages($pgScriptPath, '', 'scriptDoLoad', 'subcontent', 'layout=ajax'); - $this->set('pagingDiv', $pagingDiv); - $sql .= " order by ".addslashes($orderCol)." ".addslashes($orderVal); - - $sql .= in_array($data['doc_type'], array('pdf', 'print', 'export')) ? "" : " limit ".$this->paging->start .",". $this->paging->per_page; - - $reportList = $this->db->select($sql); - $spTextHome = $this->getLanguageTexts('home', $_SESSION['lang_code']); - $headArr = array( - 'page_url' => $this->spTextSA["Page Link"], - 'pagerank' => $_SESSION['text']['common']['MOZ Rank'], - 'score' => $_SESSION['text']['label']["Score"], - 'brocken' => $_SESSION['text']['label']["Brocken"], - 'external_links' => $this->spTextSA["External Links"], - 'total_links' => $this->spTextSA["Total Links"], - 'google_backlinks' => "Google {$spTextHome['Backlinks']}", - 'bing_backlinks' => "Bing {$spTextHome['Backlinks']}", - 'google_indexed' => "Google {$spTextHome['Indexed']}", - 'bing_indexed' => "Bing {$spTextHome['Indexed']}", - 'crawled' => $this->spTextSA['Crawled'], - 'brocken' => $_SESSION['text']['label']['Brocken'], - 'page_title' => $_SESSION['text']['label']['Title'], - 'page_description' => $_SESSION['text']['label']['Description'], - 'page_keywords' => $_SESSION['text']['label']['Keywords'], - 'comments' => $_SESSION['text']['label']['Comments'], - ); - - if ($exportVersion) { - $spText = $_SESSION['text']; - $exportContent = createExportContent(array('', $this->spTextSA["Link Reports"], '')); - $exportContent .= createExportContent(array()); - $exportContent .= createExportContent(array()); - $exportContent .= createExportContent(array($this->spTextSA['Project Url'], $projectInfo['url'])); - $exportContent .= createExportContent(array($_SESSION['text']['label']['Updated'], $projectInfo['last_updated'])); - $exportContent .= createExportContent(array($_SESSION['text']['label']['Total Results'], $this->db->noRows)); - $exportContent .= createExportContent(array()); - $exportContent .= createExportContent(array($spText['common']['No'],$headArr['page_url'],$headArr['pagerank'],$headArr['google_backlinks'],$headArr['bing_backlinks'],$headArr['google_indexed'],$headArr['bing_indexed'],$headArr['external_links'],$headArr['total_links'],$headArr['score'],$headArr['brocken'],$headArr['crawled'],$headArr['page_title'],$headArr['page_description'],$headArr['page_keywords'],$headArr['comments'])); - $auditorComp = $this->createComponent('AuditorComponent'); - foreach($reportList as $i => $listInfo) { - if ($listInfo['crawled']) { - $auditorComp->countReportPageScore($listInfo); - $comments = strip_tags(implode("\n", $auditorComp->commentInfo)); - } else { - $comments = ""; - } - $listInfo['crawled'] = $listInfo['crawled'] ? $spText['common']['Yes'] : $spText['common']['No']; - $listInfo['brocken'] = $listInfo['brocken'] ? $spText['common']['Yes'] : $spText['common']['No']; - $exportContent .= createExportContent(array($i+1, $listInfo['page_url'],$listInfo['pagerank'],$listInfo['google_backlinks'],$listInfo['bing_backlinks'],$listInfo['google_indexed'],$listInfo['bing_indexed'],$listInfo['external_links'],$listInfo['total_links'],$listInfo['score'],$listInfo['brocken'],$listInfo['crawled'],$listInfo['page_title'],$listInfo['page_description'],$listInfo['page_keywords'],$comments)); - } - exportToCsv('siteauditor_report', $exportContent); - } else { - $this->set('totalResults', $this->db->noRows); - $this->set('list', $reportList); - $this->set('pageNo', $_GET['pageno']); - $this->set('data', $data); - $this->set('headArr', $headArr); - - // if pdf export - if ($data['doc_type'] == "pdf") { - exportToPdf($this->getViewContent('siteauditor/reportlinks'), "site_auditor_report_links.pdf"); - } else { - $this->render('siteauditor/reportlinks'); - } - } - - } - - # function show the details of a page - function viewPageDetails($info='') { - $reportId = intval($info['report_id']); - if (!empty($reportId)) { - $auditorComp = $this->createComponent('AuditorComponent'); - $reportInfo = $auditorComp->getReportInfo(" and id=$reportId"); - $reportInfo['score'] = array_sum($auditorComp->countReportPageScore($reportInfo)); - $reportInfo['comments'] = $comments = implode("".$_SESSION['text']['common']['Found']." ".count($urlList)." Sitemap Urls
"); - $function = $this->smType ."SitemapFile"; - $this->deleteSitemapFiles(); - $this->$function($urlList); - $this->showSitemapFiles(); - - } - - # func to get a sitemap urls of a site - function getSitemapUrls(){ - $this->urlList = array(); - $this->crawlSitemapUrls($this->baseUrl, true); - } - - # func to crawl sitemap urls - function crawlSitemapUrls($baseUrl, $recursive=false){ - - if($this->urlList[$baseUrl]['visit'] == 1) return; - $this->urlList[$baseUrl]['visit'] = 1; - - $urlList = $this->spider->getUniqueUrls($baseUrl); - $hostName = $this->hostName; - - foreach($urlList as $href){ - if(preg_match('/\.zip$|\.gz$|\.tar$|\.png$|\.jpg$|\.jpeg$|\.gif$|\.mp3$/i', $href)) continue; - $urlInfo = @parse_url($href); - - $urlHostName = str_replace('www.', '', $urlInfo['host']); - if(empty($urlHostName)){ - $href = $this->baseUrl.$href; - }else{ - if($urlHostName != $hostName){ - continue; - } - } - - $href = $this->spider->formatUrl($href); - $href = preg_replace('/http:\/\/.*?\//i', $this->baseUrl, $href); - if(!empty( $this->excludeUrl) && stristr($href, $this->excludeUrl)) continue; - if(!isset($this->urlList[$href]['visit']) && !isset($this->urlList[$href.'/']['visit'])){ - $this->urlList[$href]['visit'] = 0; - if($recursive){ - sleep($this->sleep); - $this->crawlSitemapUrls($href,true); - } - } - } - } - - # create text sitemap file - function txtSitemapFile($urlList) { - $this->smheader = ''; - $this->smfooter = ''; - $smxml = ""; - foreach($urlList as $this->loc){ - $smxml .= $this->loc ."\n"; - } - $this->smfile = $this->section ."_sitemap1.".$this->smType; - $this->createSitemapFile($smxml); - } - - # create Html sitemap file - function htmlSitemapFile($urlList) { - $this->smheader = ''; - $this->smfooter = ''; - $smxml = ""; - foreach($urlList as $this->loc){ - $smxml .= "$this->loc- ".$this->spTextSitemap['Download sitemap file from'].": - $file -
"; - } - } - } - closedir($handle); - } - } - - function deleteSitemapFiles(){ - if ($handle = opendir(SP_TMPPATH ."/".$this->sitemapDir)) { - while (false !== ($file = readdir($handle))) { - if ( ($file != ".") && ($file != "..") ) { - if(preg_match("/".preg_quote($this->section, '/')."_sitemap\d+\.".$this->smType."/", $file, $matches)){ - unlink(SP_TMPPATH ."/".$this->sitemapDir."/$file"); - } - } - } - closedir($handle); - } - } - - # create url xml text - function createUrlXmlText() { - $xmltext = - ' -".$_SESSION['text']['common']['Found']." ".count($urlList)." Sitemap Urls
"); + $function = $this->smType ."SitemapFile"; + $this->deleteSitemapFiles(); + $this->$function($urlList); + $this->showSitemapFiles(); + + } + + # func to get a sitemap urls of a site + function getSitemapUrls(){ + $this->urlList = array(); + $this->crawlSitemapUrls($this->baseUrl, true); + } + + # func to crawl sitemap urls + function crawlSitemapUrls($baseUrl, $recursive=false){ + + if($this->urlList[$baseUrl]['visit'] == 1) return; + $this->urlList[$baseUrl]['visit'] = 1; + + $urlList = $this->spider->getUniqueUrls($baseUrl); + $hostName = $this->hostName; + + foreach($urlList as $href){ + if(preg_match('/\.zip$|\.gz$|\.tar$|\.png$|\.jpg$|\.jpeg$|\.gif$|\.mp3$/i', $href)) continue; + $urlInfo = @parse_url($href); + + $urlHostName = str_replace('www.', '', $urlInfo['host']); + if(empty($urlHostName)){ + $href = $this->baseUrl.$href; + }else{ + if($urlHostName != $hostName){ + continue; + } + } + + $href = $this->spider->formatUrl($href); + $href = preg_replace('/http:\/\/.*?\//i', $this->baseUrl, $href); + if(!empty( $this->excludeUrl) && stristr($href, $this->excludeUrl)) continue; + if(!isset($this->urlList[$href]['visit']) && !isset($this->urlList[$href.'/']['visit'])){ + $this->urlList[$href]['visit'] = 0; + if($recursive){ + sleep($this->sleep); + $this->crawlSitemapUrls($href,true); + } + } + } + } + + # create text sitemap file + function txtSitemapFile($urlList) { + $this->smheader = ''; + $this->smfooter = ''; + $smxml = ""; + foreach($urlList as $this->loc){ + $smxml .= $this->loc ."\n"; + } + $this->smfile = $this->section ."_sitemap1.".$this->smType; + $this->createSitemapFile($smxml); + } + + # create Html sitemap file + function htmlSitemapFile($urlList) { + $this->smheader = ''; + $this->smfooter = ''; + $smxml = ""; + foreach($urlList as $this->loc){ + $smxml .= "$this->loc+ ".$this->spTextSitemap['Download sitemap file from'].": + $file +
"; + } + } + } + closedir($handle); + } + } + + function deleteSitemapFiles(){ + if ($handle = opendir(SP_TMPPATH ."/".$this->sitemapDir)) { + while (false !== ($file = readdir($handle))) { + if ( ($file != ".") && ($file != "..") ) { + if(preg_match("/".preg_quote($this->section, '/')."_sitemap\d+\.".$this->smType."/", $file, $matches)){ + unlink(SP_TMPPATH ."/".$this->sitemapDir."/$file"); + } + } + } + closedir($handle); + } + } + + # create url xml text + function createUrlXmlText() { + $xmltext = + ' +