Ejemplo n.º 1
0
 /**
  * Trim if variable is a string, otherwise trim as an array
  *
  * @param  mixed $data
  * @return mixed
  */
 function trim_if_string($data)
 {
     if (is_array($data) or is_object($data)) {
         return trim_array($data);
     }
     return trim($data);
 }
Ejemplo n.º 2
0
 function storeSecurity(&$pParamHash)
 {
     if (@$this->verifyId($pParamHash['content_id'])) {
         // We'll first nuke any security mappings for this content_id
         $sql = "DELETE FROM `" . BIT_DB_PREFIX . "gatekeeper_security_map`\n\t\t\t\t\tWHERE `content_id` = ?";
         $rs = $this->mDb->query($sql, array($pParamHash['content_id']));
     }
     if (!empty($pParamHash['access_level']) || @$this->verifyId($pParamHash['security_id']) && $pParamHash['security_id'] != 'public') {
         if ($this->verifySecurity($pParamHash) && !empty($pParamHash['security_store'])) {
             trim_array($pParamHash);
             if (!empty($pParamHash['security_store'])) {
                 global $gBitUser;
                 $table = BIT_DB_PREFIX . "gatekeeper_security";
                 if (!@$this->verifyId($pParamHash['security_id'])) {
                     $pParamHash['security_store']['user_id'] = $gBitUser->mUserId;
                     $pParamHash['security_id'] = $this->mDb->GenID('gatekeeper_security_id_seq');
                     $pParamHash['security_store']['security_id'] = $pParamHash['security_id'];
                     $result = $this->mDb->associateInsert($table, $pParamHash['security_store']);
                 } else {
                     $result = $this->mDb->associateUpdate($table, $pParamHash['security_store'], array("security_id" => $pParamHash['security_id']));
                 }
             }
         }
         if (@$this->verifyId($pParamHash['content_id']) && @$this->verifyId($pParamHash['security_id'])) {
             $sql = "INSERT INTO `" . BIT_DB_PREFIX . "gatekeeper_security_map` ( `content_id`, `security_id` ) VALUES (?,?)";
             $rs = $this->mDb->query($sql, array($pParamHash['content_id'], $pParamHash['security_id']));
         }
     }
     return count($this->mErrors) == 0;
 }
Ejemplo n.º 3
0
function HookGrant_editEditeditbeforeheader()
{
    global $ref, $baseurl, $usergroup, $grant_edit_groups, $collection;
    // Do we have access to do any of this, or is it a template
    if (!in_array($usergroup, $grant_edit_groups) || $ref < 0) {
        return;
    }
    // Check for Ajax POST to delete users
    $grant_edit_action = getvalescaped("grant_edit_action", "");
    if ($grant_edit_action != "") {
        if ($grant_edit_action == "delete") {
            $remove_user = escape_check(getvalescaped("remove_user", "", TRUE));
            if ($remove_user != "") {
                sql_query("delete from grant_edit where resource='{$ref}' and user={$remove_user}");
                exit("SUCCESS");
            }
        }
        exit("FAILED");
    }
    # If 'users' is specified (i.e. access is private) then rebuild users list
    $users = getvalescaped("users", false);
    if ($users != false) {
        # Build a new list and insert
        $users = resolve_userlist_groups($users);
        $ulist = array_unique(trim_array(explode(",", $users)));
        $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')");
        if (count($urefs) > 0) {
            $inserttext = array();
            $grant_edit_expiry = getvalescaped("grant_edit_expiry", "");
            foreach ($urefs as $uref) {
                if ($grant_edit_expiry != "") {
                    $inserttext[] = $uref . ",'" . $grant_edit_expiry . "'";
                } else {
                    $inserttext[] = $uref . ",NULL";
                }
            }
            if ($collection != "") {
                global $items;
                foreach ($items as $collection_resource) {
                    sql_query("delete from grant_edit where resource='{$collection_resource}' and user in (" . implode(",", $urefs) . ")");
                    sql_query("insert into grant_edit(resource,user,expiry) values ({$collection_resource}," . join("),(" . $collection_resource . ",", $inserttext) . ")");
                    #log this
                    global $lang;
                    resource_log($collection_resource, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
                }
            } else {
                sql_query("delete from grant_edit where resource='{$ref}' and user in (" . implode(",", $urefs) . ")");
                sql_query("insert into grant_edit(resource,user,expiry) values ({$ref}," . join("),(" . $ref . ",", $inserttext) . ")");
                #log this
                global $lang;
                resource_log($ref, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
            }
        }
    }
    return true;
}
Ejemplo n.º 4
0
function comparble_version($version_number)
{
    $version_number = explode(".", $version_number);
    $version_number = array_map("intval", $version_number);
    $version_number = trim_array($version_number);
    $version_number = array_map(function ($e) {
        return str_pad($e, 10, "0", STR_PAD_LEFT);
    }, $version_number);
    return implode(".", $version_number);
}
Ejemplo n.º 5
0
 /**
  * Compress content
  *
  * @return Response
  */
 public function compress(Request $request, Response $response)
 {
     $acceptEncoding = $request->getHeaderLine('accept-encoding');
     $encodings = array_flip(trim_array(explode(',', $acceptEncoding)));
     if (isset($encodings['gzip'])) {
         return $this->compressBody($response, 'gzip', 'gzcompress');
     }
     if (isset($encodings['deflate'])) {
         return $this->compressBody($response, 'deflate', 'gzdeflate');
     }
     return $response;
 }
Ejemplo n.º 6
0
 public function index($category = null, $products = null)
 {
     if (is_null($category)) {
         //show all categories
         /*  breadcrumbs */
         $this->breadcrumbs->unshift('products', site_url('products'));
         $this->breadcrumbs->unshift('Home', site_url('home'));
         $this->data['title'] = 'Our categories';
         $cat = $this->model_products->getCategories();
         $this->data['content'] = $this->smarty->load('categories', $cat);
     } elseif (!is_null($category) && is_null($products)) {
         //if category part in the URL and no product number
         $category = $this->security->xss_clean($category);
         $this->data['title'] = $category . '- items';
         $prod = $this->model_products->getProducts($category);
         if ($prod) {
             /*  breadcrumbs */
             $this->breadcrumbs->unshift($prod[0]["name"], site_url("products/") . $prod[0]['cat_machine']);
             $this->breadcrumbs->unshift('products', site_url('products'));
             $this->breadcrumbs->unshift('Home', site_url('home'));
             $this->data['title'] = 'Phoneshop - ' . $prod[0]["cat_machine"];
             $this->data['content'] = $this->smarty->load('category', $prod, 'category');
         }
     } elseif (!is_null($category) && !is_null($products)) {
         //if category part in the URL and no product number
         $products = $this->security->xss_clean($products);
         $item = $this->model_products->getItem($products);
         $images = explode(',', $item['images']);
         $images = trim_array($images);
         if ($item) {
             /*  breadcrumbs */
             $this->breadcrumbs->unshift($item["title"], site_url("products/") . $item['cat_name'] . '/' . $item['machine_name']);
             $this->breadcrumbs->unshift($item["cat_title"], site_url("products") . '/' . $item['cat_name']);
             $this->breadcrumbs->unshift('products', site_url('products'));
             $this->breadcrumbs->unshift('Home', site_url('home'));
             $this->smarty->assign('images', $images);
             $this->data['title'] = 'Phoneshop - ' . $item['title'];
             $this->data['content'] = $this->smarty->load('item', $item);
         }
     }
     $this->load->view('templates/main', $this->data);
     //show the template main
 }
Ejemplo n.º 7
0
function email_collection($colrefs,$collectionname,$fromusername,$userlist,$message,$feedback,$access=-1,$expires="",$useremail="",$from_name="",$cc="",$themeshare=false,$themename="",$themeurlsuffix="")
	{
	# Attempt to resolve all users in the string $userlist to user references.
	# Add $collection to these user's 'My Collections' page
	# Send them an e-mail linking to this collection
	#  handle multiple collections (comma seperated list)
	global $baseurl,$email_from,$applicationname,$lang,$userref, $email_multi_collections ;
	
	if ($useremail==""){$useremail=$email_from;}
	
	if (trim($userlist)=="") {return ($lang["mustspecifyoneusername"]);}
	$userlist=resolve_userlist_groups($userlist);
	$ulist=trim_array(explode(",",$userlist));
	$emails=array();
	$key_required=array();
	if ($feedback) {$feedback=1;} else {$feedback=0;}
	$reflist=trim_array(explode(",",$colrefs));
	
	$emails_keys=resolve_user_emails($ulist);
	$emails=$emails_keys['emails'];
	$key_required=$emails_keys['key_required'];

	# Add the collection(s) to the user's My Collections page
	$urefs=sql_array("select ref value from user where username in ('" . join("','",$ulist) . "')");
	if (count($urefs)>0)
		{
		# Delete any existing collection entries
		sql_query("delete from user_collection where collection in ('" .join("','", $reflist) . "') and user in ('" . join("','",$urefs) . "')");
		
		# Insert new user_collection row(s)
		#loop through the collections
			for ($nx1=0;$nx1<count($reflist);$nx1++)
			{	#loop through the users
				for ($nx2=0;$nx2<count($urefs);$nx2++)
				{
		sql_query("insert into user_collection(collection,user,request_feedback) values ($reflist[$nx1], $urefs[$nx2], $feedback )");
		if ($access == 0) {
			foreach (get_collection_resources($reflist[$nx1]) as $resource)	{
				open_access_to_user($urefs[$nx2],$resource,$expires);
			}
		}
				
			#log this
		collection_log($reflist[$nx1],"S",0, sql_value ("select username as value from user where ref = $urefs[$nx2]",""));

				}
			}
		}
	
	# Send an e-mail to each resolved user
	
	# htmlbreak is for composing list
	$htmlbreak="\r\n";
	global $use_phpmailer;
	if ($use_phpmailer){$htmlbreak="<br><br>";$htmlbreaksingle="<br>";} 
	
	if ($fromusername==""){$fromusername=$applicationname;} // fromusername is used for describing the sender's name inside the email
	if ($from_name==""){$from_name=$applicationname;} // from_name is for the email headers, and needs to match the email address (app name or user name)
	
	$templatevars['message']=str_replace(array("\\n","\\r","\\"),array("\n","\r",""),$message);	
	if (trim($templatevars['message'])==""){$templatevars['message']=$lang['nomessage'];} 
	
	$templatevars['fromusername']=$fromusername;
	$templatevars['from_name']=$from_name;
	
	if(count($reflist)>1){$subject=$applicationname.": ".$lang['mycollections'];}
	else { $subject=$applicationname.": ".$collectionname;}
	
	if ($fromusername==""){$fromusername=$applicationname;}
	
	$externalmessage=$lang["emailcollectionmessageexternal"];
	$internalmessage=$lang["emailcollectionmessage"];
	$viewlinktext=$lang["clicklinkviewcollection"];
	if ($themeshare) // Change the text if sharing a theme category
		{
		$externalmessage=$lang["emailthemecollectionmessageexternal"];
		$internalmessage=$lang["emailthememessage"];
		$viewlinktext=$lang["clicklinkviewcollections"];
		}
		
	##  loop through recipients
	for ($nx1=0;$nx1<count($emails);$nx1++)
		{
		## loop through collections
		$list="";
		$list2="";
		$origviewlinktext=$viewlinktext; // Save this text as we may change it for internal theme shares for this user
		if ($themeshare && !$key_required[$nx1]) # don't send a whole list of collections if internal, just send the theme category URL
			{
			$url="";
			$subject=$applicationname.": " . $themename;
			$url=$baseurl . "/pages/themes.php" . $themeurlsuffix;			
			$viewlinktext=$lang["clicklinkviewthemes"];
			$emailcollectionmessageexternal=false;
			if ($use_phpmailer){
					$link="<a href=\"$url\">" . $themename . "</a>";	
					
					$list.= $htmlbreak.$link;	
					// alternate list style				
					$list2.=$htmlbreak.$themename.' -'.$htmlbreaksingle.$url;
					$templatevars['list2']=$list2;					
					}
				else
					{
					$list.= $htmlbreak.$url;
					}
			for ($nx2=0;$nx2<count($reflist);$nx2++)
				{				
				#log this
				collection_log($reflist[$nx2],"E",0, $emails[$nx1]);
				}
			
			}
		else
			{
			for ($nx2=0;$nx2<count($reflist);$nx2++)
				{
				$url="";
				$key="";
				$emailcollectionmessageexternal=false;
				# Do we need to add an external access key for this user (e-mail specified rather than username)?
				if ($key_required[$nx1])
					{
					$k=generate_collection_access_key($reflist[$nx2],$feedback,$emails[$nx1],$access,$expires);
					$key="&k=". $k;
					$emailcollectionmessageexternal=true;
					}
				$url=$baseurl . 	"/?c=" . $reflist[$nx2] . $key;		
				$collection = array();
				$collection = sql_query("select name,savedsearch from collection where ref='$reflist[$nx2]'");
				if ($collection[0]["name"]!="") {$collection_name = i18n_get_collection_name($collection[0]);}
				else {$collection_name = $reflist[$nx2];}
				if ($use_phpmailer){
					$link="<a href=\"$url\">$collection_name</a>";	
					$list.= $htmlbreak.$link;	
					// alternate list style				
					$list2.=$htmlbreak.$collection_name.' -'.$htmlbreaksingle.$url;
					$templatevars['list2']=$list2;					
					}
				else
					{
					$list.= $htmlbreak . $collection_name . $htmlbreak . $url . $htmlbreak;
					}
				#log this
				collection_log($reflist[$nx2],"E",0, $emails[$nx1]);
				}
			}
		//$list.=$htmlbreak;	
		$templatevars['list']=$list;
		$templatevars['from_name']=$from_name;
		if ($emailcollectionmessageexternal ){
			$template=($themeshare)?"emailthemeexternal":"emailcollectionexternal";
		}
		else {
			$template=($themeshare)?"emailtheme":"emailcollection";
		}
		$body=$templatevars['fromusername']." " . (($emailcollectionmessageexternal)?$externalmessage:$internalmessage) . "\n\n" . $templatevars['message']."\n\n" . $viewlinktext ."\n\n".$templatevars['list'];
		#exit ($body . "<br>" . $viewlinktext);	
		send_mail($emails[$nx1],$subject,$body,$fromusername,$useremail,$template,$templatevars,$from_name,$cc);
		$viewlinktext=$origviewlinktext;
		}
		
	# Return an empty string (all OK).
	return "";
	}
Ejemplo n.º 8
0
function check_view_display_condition($fields, $n)
{
    #Check if field has a display condition set
    $displaycondition = true;
    if ($fields[$n]["display_condition"] != "") {
        //echo $fields[$n]["display_condition"] . "<br>";
        $fieldstocheck = array();
        #' Set up array to use in jQuery script function
        $s = explode(";", $fields[$n]["display_condition"]);
        $condref = 0;
        foreach ($s as $condition) {
            $displayconditioncheck = false;
            $s = explode("=", $condition);
            for ($cf = 0; $cf < count($fields); $cf++) {
                if ($s[0] == $fields[$cf]["name"]) {
                    $checkvalues = $s[1];
                    $validvalues = explode("|", strtoupper($checkvalues));
                    $v = trim_array(explode(",", strtoupper($fields[$cf]["value"])));
                    foreach ($validvalues as $validvalue) {
                        if (in_array($validvalue, $v)) {
                            $displayconditioncheck = true;
                        }
                        # this is  a valid value
                    }
                    if (!$displayconditioncheck) {
                        $displaycondition = false;
                    }
                }
            }
            # see if next field needs to be checked
            $condref++;
        }
        # check next condition
    }
    return $displaycondition;
}
Ejemplo n.º 9
0
<?php

/* --------Drop down list ---------------- */
# Translate all options
$options = trim_array(explode(",", $fields[$n]["options"]));
$adjusted_dropdownoptions = hook("adjustdropdownoptions");
if ($adjusted_dropdownoptions) {
    $options = $adjusted_dropdownoptions;
}
$option_trans = array();
for ($m = 0; $m < count($options); $m++) {
    $option_trans[$options[$m]] = i18n_get_translated($options[$m]);
}
if ($auto_order_checkbox) {
    asort($option_trans);
}
if (substr($value, 0, 1) == ',') {
    $value = substr($value, 1);
}
// strip the leading comma if it exists
?>
<select class="stdwidth" name="<?php 
echo $name;
?>
" id="<?php 
echo $name;
?>
" <?php 
echo $help_js;
if ($edit_autosave) {
    ?>
Ejemplo n.º 10
0
function trim_array(&$var)
{
    if (is_string($var)) {
        $var = trim($var);
    } else {
        if (is_array($var)) {
            foreach ($var as $key => $value) {
                trim_array($var[$key]);
            }
        }
    }
}
Ejemplo n.º 11
0
function filter_match($filter,$name,$value)
	{
	# In the given filter string, does name/value match?
	# Returns:
	# 0 = no match for name
	# 1 = matched name but value was not present
	# 2 = matched name and value was correct
	$s=explode(";",$filter);
	foreach ($s as $condition)
		{
		$s=explode("=",$condition);
		$checkname=$s[0];
		if ($checkname==$name)
			{
			$checkvalues=$s[1];
			
			$s=explode("|",strtoupper($checkvalues));
			$v=trim_array(explode(",",strtoupper($value)));
			foreach ($s as $checkvalue)
				{
				if (in_array($checkvalue,$v)) {return 2;}
				}
			return 1;
			}
		}
	return 0;
	}
Ejemplo n.º 12
0
                } else {
                    $url = $groupInfo['after_registration_page'];
                }
            }
            header('Location: ' . $url);
            exit;
        }
    } else {
        $gBitSystem->setHttpStatus(HttpStatusCodes::HTTP_BAD_REQUEST);
        $gBitSmarty->assignByRef('errors', $newUser->mErrors);
    }
    $gBitSmarty->assignByRef('reg', $reg);
} else {
    if ($gBitSystem->isFeatureActive('custom_user_fields')) {
        $fields = explode(',', $gBitSystem->getConfig('custom_user_fields'));
        trim_array($fields);
        $gBitSmarty->assign('customFields', $fields);
    }
    for ($i = 0; $i < BaseAuth::getAuthMethodCount(); $i++) {
        $instance = BaseAuth::init($i);
        if ($instance && $instance->canManageAuth()) {
            $auth_reg_fields = $instance->getRegistrationFields();
            foreach (array_keys($auth_reg_fields) as $auth_field) {
                $auth_reg_fields[$auth_field]['value'] = $auth_reg_fields[$auth_field]['default'];
            }
            $gBitSmarty->assign('auth_reg_fields', $auth_reg_fields);
            break;
        }
    }
}
$languages = array();
Ejemplo n.º 13
0
function check_display_condition($n, $field)
{
    global $fields, $scriptconditions, $required_fields_exempt;
    $displaycondition = true;
    $s = explode(";", $field["display_condition"]);
    $condref = 0;
    foreach ($s as $condition) {
        $displayconditioncheck = false;
        $s = explode("=", $condition);
        for ($cf = 0; $cf < count($fields); $cf++) {
            if ($s[0] == $fields[$cf]["name"]) {
                $scriptconditions[$condref]["field"] = $fields[$cf]["ref"];
                # add new jQuery code to check value
                $scriptconditions[$condref]['type'] = $fields[$cf]['type'];
                $scriptconditions[$condref]['options'] = $fields[$cf]['options'];
                $checkvalues = $s[1];
                $validvalues = explode("|", strtoupper($checkvalues));
                $scriptconditions[$condref]["valid"] = "\"";
                $scriptconditions[$condref]["valid"] .= implode("\",\"", $validvalues);
                $scriptconditions[$condref]["valid"] .= "\"";
                $v = trim_array(explode(",", strtoupper($fields[$cf]["value"])));
                foreach ($validvalues as $validvalue) {
                    if (in_array($validvalue, $v)) {
                        $displayconditioncheck = true;
                    }
                    # this is  a valid value
                }
                if (!$displayconditioncheck) {
                    $displaycondition = false;
                    $required_fields_exempt[] = $field["ref"];
                }
                #add jQuery code to update on changes
                if ($fields[$cf]["type"] == 2) {
                    # construct the value from the ticked boxes
                    # Note: it seems wrong to start with a comma, but this ensures it is treated as a comma separated list by split_keywords(), so if just one item is selected it still does individual word adding, so 'South Asia' is split to 'South Asia','South','Asia'.
                    $options = trim_array(explode(",", $fields[$cf]["options"]));
                    ?>
<script type="text/javascript">
						jQuery(document).ready(function() {<?php 
                    for ($m = 0; $m < count($options); $m++) {
                        $checkname = $fields[$cf]["ref"] . "_" . md5($options[$m]);
                        echo "\n\t\t\t\t\t\t\t\tjQuery('input[name=\"" . $checkname . "\"]').change(function (){\n\t\t\t\t\t\t\t\t\tcheckDisplayCondition" . $field["ref"] . "();\n\t\t\t\t\t\t\t\t\t});";
                    }
                    ?>
							});
						</script><?php 
                } else {
                    if ($fields[$cf]['type'] == 12) {
                        $options = explode(',', $fields[$cf]['options']);
                        ?>

							<script type="text/javascript">
							jQuery(document).ready(function() {

							<?php 
                        foreach ($options as $option) {
                            $element_id = 'field_' . $fields[$cf]['ref'] . '_' . sha1($option);
                            $jquery = sprintf('
										jQuery("#%s").change(function() {
											checkDisplayCondition%s();
										});
								', $element_id, $field["ref"]);
                            echo $jquery;
                        }
                        ?>
							
							});
							</script>

							<?php 
                    } else {
                        ?>
						<script type="text/javascript">
						jQuery(document).ready(function() {
							jQuery('#field_<?php 
                        echo $fields[$cf]["ref"];
                        ?>
').change(function (){

							checkDisplayCondition<?php 
                        echo $field["ref"];
                        ?>
();

							});
						});
						</script>
					<?php 
                    }
                }
            }
        }
        # see if next field needs to be checked
        $condref++;
    }
    # check next condition
    ?>
	<script type="text/javascript">
	function checkDisplayCondition<?php 
    echo $field["ref"];
    ?>
()
		{
		<?php 
    echo "field" . $field["ref"] . "status=jQuery('#question_" . $n . "').css('display');\n\t\t";
    echo "newfield" . $field["ref"] . "status='none';\n\t\t";
    echo "newfield" . $field["ref"] . "provisional=true;\n\t\t";
    foreach ($scriptconditions as $scriptcondition) {
        echo "newfield" . $field["ref"] . "provisionaltest=false;\n\t\t\t";
        echo "if (jQuery('#field_" . $scriptcondition["field"] . "').length!=0)\n\t\t\t\t{";
        echo "\n\t\t\t\tfieldcheck" . $scriptcondition["field"] . "=jQuery('#field_" . $scriptcondition["field"] . "').val().toUpperCase();\n\t\t\t\t";
        echo "fieldvalues" . $scriptcondition["field"] . "=fieldcheck" . $scriptcondition["field"] . ".split(',');\n\t\t\t\t//alert(fieldvalues" . $scriptcondition["field"] . ");\n\t\t\t\t}";
        echo "\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t";
        # Handle Radio Buttons type:
        if ($scriptcondition['type'] == 12) {
            $scriptcondition["options"] = explode(',', $scriptcondition["options"]);
            foreach ($scriptcondition["options"] as $key => $value) {
                $scriptcondition["options"][$key] = sha1($value);
            }
            $scriptcondition["options"] = implode(',', $scriptcondition["options"]);
            ?>

					var options_string = '<?php 
            echo $scriptcondition["options"];
            ?>
';

					var field<?php 
            echo $scriptcondition["field"];
            ?>
_options = options_string.split(',');
					
					var checked = null;

					for(var i=0; i < field<?php 
            echo $scriptcondition["field"];
            ?>
_options.length; i++){
						
						if(jQuery('#field_<?php 
            echo $scriptcondition["field"];
            ?>
_' + field<?php 
            echo $scriptcondition["field"];
            ?>
_options[i]).is(':checked')) {
							checked = jQuery('#field_<?php 
            echo $scriptcondition["field"];
            ?>
_' + field<?php 
            echo $scriptcondition["field"];
            ?>
_options[i] + ':checked').val();
							checked = checked.toUpperCase();
						}

					}

					fieldokvalues<?php 
            echo $scriptcondition["field"];
            ?>
 = [<?php 
            echo $scriptcondition["valid"];
            ?>
];

					if(checked !== null && jQuery.inArray(checked, fieldokvalues<?php 
            echo $scriptcondition["field"];
            ?>
) > -1) {
						newfield<?php 
            echo $field["ref"];
            ?>
provisionaltest = true;
					}
				
				<?php 
        }
        echo "fieldvalues" . $scriptcondition["field"] . "=new Array();\n\t\t\t\t";
        echo "checkedvals" . $scriptcondition["field"] . "=jQuery('input[name^=" . $scriptcondition["field"] . "_]')\n\t\t\t\t";
        echo "jQuery.each(checkedvals" . $scriptcondition["field"] . ",function(){\n\t\t\t\t\tif (jQuery(this).is(':checked'))\n\t\t\t\t\t\t{\n\t\t\t\t\t\tchecktext" . $scriptcondition["field"] . "=jQuery(this).parent().next().text().toUpperCase();\n\t\t\t\t\t\tchecktext" . $scriptcondition["field"] . " = jQuery.trim(checktext" . $scriptcondition["field"] . ");\n\t\t\t\t\t\tfieldvalues" . $scriptcondition["field"] . ".push(checktext" . $scriptcondition["field"] . ");\n\t\t\t\t\t\t//alert(fieldvalues" . $scriptcondition["field"] . ");\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}";
        echo "fieldokvalues" . $scriptcondition["field"] . "=new Array();\n\t\t\t";
        echo "fieldokvalues" . $scriptcondition["field"] . "=[" . $scriptcondition["valid"] . "];\n\t\t\t";
        echo "jQuery.each(fieldvalues" . $scriptcondition["field"] . ",function(f,v){\n\t\t\t\t\t//alert(\"checking value \" + fieldvalues" . $scriptcondition["field"] . " + \" against \" + fieldokvalues" . $scriptcondition["field"] . ");\n\t\t\t\t\t//alert(jQuery.inArray(fieldvalues" . $scriptcondition["field"] . ",fieldokvalues" . $scriptcondition["field"] . "));\n\t\t\t\t\tif ((jQuery.inArray(v,fieldokvalues" . $scriptcondition["field"] . "))>-1 || (fieldvalues" . $scriptcondition["field"] . " ==fieldokvalues" . $scriptcondition["field"] . " ))\n\t\t\t\t\t\t{\n\t\t\t\t\t\tnewfield" . $field["ref"] . "provisionaltest=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\tif (newfield" . $field["ref"] . "provisionaltest==false)\n\t\t\t\t\t{newfield" . $field["ref"] . "provisional=false;}\n\t\t\t\t";
    }
    echo "\n\t\t\texemptfieldsval=jQuery('#exemptfields').val();\n\t\t\texemptfieldsarr=exemptfieldsval.split(',');\n\t\t\tif (newfield" . $field["ref"] . "provisional==true)\n\t\t\t\t{\n\t\t\t\tif (jQuery.inArray(" . $field["ref"] . ",exemptfieldsarr))\n\t\t\t\t\t{\n\t\t\t\t\texemptfieldsarr.splice(jQuery.inArray(" . $field["ref"] . ", exemptfieldsarr), 1 );\n\t\t\t\t\t}\n\t\t\t\tnewfield" . $field["ref"] . "status='block'\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\n\n\t\t\t\tif ((jQuery.inArray(" . $field["ref"] . ",exemptfieldsarr))==-1)\n\t\t\t\t\t{\n\t\t\t\t\texemptfieldsarr.push(" . $field["ref"] . ")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tjQuery('#exemptfields').val(exemptfieldsarr.join(", "));\n\n\n\t\t\t";
    echo "if (newfield" . $field["ref"] . "status!=field" . $field["ref"] . "status)\n\t\t\t\t{\n\t\t\t\tjQuery('#question_" . $n . "').slideToggle();\n\t\t\t\tif (jQuery('#question_" . $n . "').css('display')=='block')\n\t\t\t\t\t{jQuery('#question_" . $n . "').css('border-top','');}\n\t\t\t\telse\n\t\t\t\t\t{jQuery('#question_" . $n . "').css('border-top','none');}\n\t\t\t\t}\n\n\t\t\t\t";
    ?>
}
	</script>
	<?php 
    return $displaycondition;
}
Ejemplo n.º 14
0
 function setArticleTags()
 {
     $id = db_escape_string($_REQUEST["id"]);
     $tags_str = db_escape_string($_REQUEST["tags_str"]);
     $tags = array_unique(trim_array(explode(",", $tags_str)));
     db_query($this->link, "BEGIN");
     $result = db_query($this->link, "SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\tref_id = '{$id}' AND owner_uid = '" . $_SESSION["uid"] . "' LIMIT 1");
     if (db_num_rows($result) == 1) {
         $tags_to_cache = array();
         $int_id = db_fetch_result($result, 0, "int_id");
         db_query($this->link, "DELETE FROM ttrss_tags WHERE\n\t\t\t\tpost_int_id = {$int_id} AND owner_uid = '" . $_SESSION["uid"] . "'");
         foreach ($tags as $tag) {
             $tag = sanitize_tag($tag);
             if (!tag_is_valid($tag)) {
                 continue;
             }
             if (preg_match("/^[0-9]*\$/", $tag)) {
                 continue;
             }
             //					print "<!-- $id : $int_id : $tag -->";
             if ($tag != '') {
                 db_query($this->link, "INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t(post_int_id, owner_uid, tag_name) VALUES ('{$int_id}', '" . $_SESSION["uid"] . "', '{$tag}')");
             }
             array_push($tags_to_cache, $tag);
         }
         /* update tag cache */
         sort($tags_to_cache);
         $tags_str = join(",", $tags_to_cache);
         db_query($this->link, "UPDATE ttrss_user_entries\n\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$id}'\n\t\t\t\t\t\tAND owner_uid = " . $_SESSION["uid"]);
     }
     db_query($this->link, "COMMIT");
     $tags = get_article_tags($this->link, $id);
     $tags_str = format_tags_string($tags, $id);
     $tags_str_full = join(", ", $tags);
     if (!$tags_str_full) {
         $tags_str_full = __("no tags");
     }
     print json_encode(array("tags_str" => array("id" => $id, "content" => $tags_str, "content_full" => $tags_str_full)));
 }
function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false)
{
    $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
    _debug("start", $debug_enabled);
    $result = db_query("SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,last_updated,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state, auth_pass_encrypted,\n\t\t\t(SELECT max(date_entered) FROM\n\t\t\t\tttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '{$feed}') AS last_article_timestamp\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
    if (db_num_rows($result) == 0) {
        _debug("feed {$feed} NOT FOUND/SKIPPED", $debug_enabled);
        return false;
    }
    $last_updated = db_fetch_result($result, 0, "last_updated");
    $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
    if (defined('_DISABLE_HTTP_304')) {
        $last_article_timestamp = 0;
    }
    $owner_uid = db_fetch_result($result, 0, "owner_uid");
    $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result, 0, "mark_unread_on_update"));
    $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
    $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result, 0, "auth_pass_encrypted"));
    db_query("UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'");
    $auth_login = db_fetch_result($result, 0, "auth_login");
    $auth_pass = db_fetch_result($result, 0, "auth_pass");
    if ($auth_pass_encrypted) {
        require_once "crypt.php";
        $auth_pass = decrypt_string($auth_pass);
    }
    $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
    $fetch_url = db_fetch_result($result, 0, "feed_url");
    $feed = db_escape_string($feed);
    $date_feed_processed = date('Y-m-d H:i');
    $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
    $pluginhost = new PluginHost();
    $pluginhost->set_debug($debug_enabled);
    $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
    $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
    $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
    $pluginhost->load_data();
    $rss = false;
    $rss_hash = false;
    $force_refetch = isset($_REQUEST["force_refetch"]);
    if (file_exists($cache_filename) && is_readable($cache_filename) && !$auth_login && !$auth_pass && filemtime($cache_filename) > time() - 30) {
        _debug("using local cache.", $debug_enabled);
        @($feed_data = file_get_contents($cache_filename));
        if ($feed_data) {
            $rss_hash = sha1($feed_data);
        }
    } else {
        _debug("local cache will not be used for this feed", $debug_enabled);
    }
    if (!$rss) {
        foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
            $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed);
        }
        if (!$feed_data) {
            _debug("fetching [{$fetch_url}]...", $debug_enabled);
            _debug("If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', $last_article_timestamp), $debug_enabled);
            $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT, $force_refetch ? 0 : $last_article_timestamp);
            global $fetch_curl_used;
            if (!$fetch_curl_used) {
                $tmp = @gzdecode($feed_data);
                if ($tmp) {
                    $feed_data = $tmp;
                }
            }
            $feed_data = trim($feed_data);
            _debug("fetch done.", $debug_enabled);
            /* if ($feed_data) {
            					$error = verify_feed_xml($feed_data);
            
            					if ($error) {
            						_debug("error verifying XML, code: " . $error->code, $debug_enabled);
            
            						if ($error->code == 26) {
            							_debug("got error 26, trying to decode entities...", $debug_enabled);
            
            							$feed_data = html_entity_decode($feed_data, ENT_COMPAT, 'UTF-8');
            
            							$error = verify_feed_xml($feed_data);
            
            							if ($error) $feed_data = '';
            						}
            					}
            				} */
        }
        if (!$feed_data) {
            global $fetch_last_error;
            global $fetch_last_error_code;
            _debug("unable to fetch: {$fetch_last_error} [{$fetch_last_error_code}]", $debug_enabled);
            $error_escaped = '';
            // If-Modified-Since
            if ($fetch_last_error_code != 304) {
                $error_escaped = db_escape_string($fetch_last_error);
            } else {
                _debug("source claims data not modified, nothing to do.", $debug_enabled);
            }
            db_query("UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
            return;
        }
    }
    foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
        $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
    }
    // set last update to now so if anything *simplepie* crashes later we won't be
    // continuously failing on the same feed
    //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
    if (!$rss) {
        $rss = new FeedParser($feed_data);
        $rss->init();
    }
    //		print_r($rss);
    $feed = db_escape_string($feed);
    if (!$rss->error()) {
        // cache data for later
        if (!$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
            $new_rss_hash = sha1($rss_data);
            if ($new_rss_hash != $rss_hash && count($rss->get_items()) > 0) {
                _debug("saving {$cache_filename}", $debug_enabled);
                @file_put_contents($cache_filename, $feed_data);
            }
        }
        // We use local pluginhost here because we need to load different per-user feed plugins
        $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
        _debug("processing feed data...", $debug_enabled);
        //			db_query("BEGIN");
        if (DB_TYPE == "pgsql") {
            $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
        } else {
            $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
        }
        $result = db_query("SELECT title,site_url,owner_uid,favicon_avg_color,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
        $registered_title = db_fetch_result($result, 0, "title");
        $orig_site_url = db_fetch_result($result, 0, "site_url");
        $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check"));
        $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
        $owner_uid = db_fetch_result($result, 0, "owner_uid");
        $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
        _debug("site_url: {$site_url}", $debug_enabled);
        _debug("feed_title: " . $rss->get_title(), $debug_enabled);
        if ($favicon_needs_check || $force_refetch) {
            /* terrible hack: if we crash on floicon shit here, we won't check
             * the icon avgcolor again (unless the icon got updated) */
            $favicon_file = ICONS_DIR . "/{$feed}.ico";
            $favicon_modified = @filemtime($favicon_file);
            _debug("checking favicon...", $debug_enabled);
            check_feed_favicon($site_url, $feed);
            $favicon_modified_new = @filemtime($favicon_file);
            if ($favicon_modified_new > $favicon_modified) {
                $favicon_avg_color = '';
            }
            if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
                require_once "colors.php";
                db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE\n\t\t\t\t\t\t\tid = '{$feed}'");
                $favicon_color = db_escape_string(calculate_avg_color($favicon_file));
                $favicon_colorstring = ",favicon_avg_color = '" . $favicon_color . "'";
            } else {
                if ($favicon_avg_color == 'fail') {
                    _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
                }
            }
            db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\t{$favicon_colorstring}\n\t\t\t\t\tWHERE id = '{$feed}'");
        }
        if (!$registered_title || $registered_title == "[Unknown]") {
            $feed_title = db_escape_string($rss->get_title());
            if ($feed_title) {
                _debug("registering title: {$feed_title}", $debug_enabled);
                db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\t\ttitle = '{$feed_title}' WHERE id = '{$feed}'");
            }
        }
        if ($site_url && $orig_site_url != $site_url) {
            db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\tsite_url = '{$site_url}' WHERE id = '{$feed}'");
        }
        _debug("loading filters & labels...", $debug_enabled);
        $filters = load_filters($feed, $owner_uid);
        $labels = get_all_labels($owner_uid);
        _debug("" . count($filters) . " filters loaded.", $debug_enabled);
        $items = $rss->get_items();
        if (!is_array($items)) {
            _debug("no articles found.", $debug_enabled);
            db_query("UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
            return;
            // no articles
        }
        if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
            _debug("checking for PUSH hub...", $debug_enabled);
            $feed_hub_url = false;
            $links = $rss->get_links('hub');
            if ($links && is_array($links)) {
                foreach ($links as $l) {
                    $feed_hub_url = $l;
                    break;
                }
            }
            _debug("feed hub url: {$feed_hub_url}", $debug_enabled);
            if ($feed_hub_url && function_exists('curl_init') && !ini_get("open_basedir")) {
                require_once 'lib/pubsubhubbub/subscriber.php';
                $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}";
                $s = new Subscriber($feed_hub_url, $callback_url);
                $rc = $s->subscribe($fetch_url);
                _debug("feed hub url found, subscribe request sent.", $debug_enabled);
                db_query("UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'");
            }
        }
        _debug("processing articles...", $debug_enabled);
        foreach ($items as $item) {
            if ($_REQUEST['xdebug'] == 3) {
                print_r($item);
            }
            $entry_guid = $item->get_id();
            if (!$entry_guid) {
                $entry_guid = $item->get_link();
            }
            if (!$entry_guid) {
                $entry_guid = make_guid_from_title($item->get_title());
            }
            _debug("f_guid {$entry_guid}", $debug_enabled);
            if (!$entry_guid) {
                continue;
            }
            $entry_guid = "{$owner_uid},{$entry_guid}";
            $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
            _debug("guid {$entry_guid} / {$entry_guid_hashed}", $debug_enabled);
            $entry_timestamp = "";
            $entry_timestamp = $item->get_date();
            _debug("orig date: " . $item->get_date(), $debug_enabled);
            if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
                $entry_timestamp = time();
                $no_orig_date = 'true';
            } else {
                $no_orig_date = 'false';
            }
            $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
            _debug("date {$entry_timestamp} [{$entry_timestamp_fmt}]", $debug_enabled);
            //				$entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
            //				$entry_title = decode_numeric_entities($entry_title);
            $entry_title = $item->get_title();
            $entry_link = rewrite_relative_url($site_url, $item->get_link());
            _debug("title {$entry_title}", $debug_enabled);
            _debug("link {$entry_link}", $debug_enabled);
            if (!$entry_title) {
                $entry_title = date("Y-m-d H:i:s", $entry_timestamp);
            }
            $entry_content = $item->get_content();
            if (!$entry_content) {
                $entry_content = $item->get_description();
            }
            if ($_REQUEST["xdebug"] == 2) {
                print "content: ";
                print $entry_content;
                print "\n";
            }
            $entry_comments = $item->get_comments_url();
            $entry_author = $item->get_author();
            $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
            $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
            $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
            $num_comments = (int) $item->get_comments_count();
            _debug("author {$entry_author}", $debug_enabled);
            _debug("num_comments: {$num_comments}", $debug_enabled);
            _debug("looking for tags...", $debug_enabled);
            // parse <category> entries into tags
            $additional_tags = array();
            $additional_tags_src = $item->get_categories();
            if (is_array($additional_tags_src)) {
                foreach ($additional_tags_src as $tobj) {
                    array_push($additional_tags, $tobj);
                }
            }
            $entry_tags = array_unique($additional_tags);
            for ($i = 0; $i < count($entry_tags); $i++) {
                $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
            }
            _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
            _debug("done collecting data.", $debug_enabled);
            // TODO: less memory-hungry implementation
            _debug("applying plugin filters..", $debug_enabled);
            // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
            $result = db_query("SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries\n\t\t\t\t\tWHERE ref_id = id AND (guid = '" . db_escape_string($entry_guid) . "' OR guid = '{$entry_guid_hashed}') AND owner_uid = {$owner_uid}");
            if (db_num_rows($result) != 0) {
                $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
                $stored_article = array("title" => db_fetch_result($result, 0, "title"), "content" => db_fetch_result($result, 0, "content"), "link" => db_fetch_result($result, 0, "link"), "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")), "author" => db_fetch_result($result, 0, "author"));
            } else {
                $entry_plugin_data = "";
                $stored_article = array();
            }
            $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "tags" => $entry_tags, "plugin_data" => $entry_plugin_data, "author" => $entry_author, "stored" => $stored_article);
            foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
                $article = $plugin->hook_article_filter($article);
            }
            $entry_tags = $article["tags"];
            $entry_guid = db_escape_string($entry_guid);
            $entry_title = db_escape_string($article["title"]);
            $entry_author = db_escape_string($article["author"]);
            $entry_link = db_escape_string($article["link"]);
            $entry_plugin_data = db_escape_string($article["plugin_data"]);
            $entry_content = $article["content"];
            // escaped below
            _debug("plugin data: {$entry_plugin_data}", $debug_enabled);
            if ($cache_images && is_writable(CACHE_DIR . '/images')) {
                cache_images($entry_content, $site_url, $debug_enabled);
            }
            $entry_content = db_escape_string($entry_content, false);
            $content_hash = "SHA1:" . sha1($entry_content);
            db_query("BEGIN");
            $result = db_query("SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE (guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}')");
            if (db_num_rows($result) == 0) {
                _debug("base guid [{$entry_guid}] not found", $debug_enabled);
                // base post entry does not exist, create it
                $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid_hashed}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$content_hash}',\n\t\t\t\t\t\t\t{$no_orig_date},\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$date_feed_processed}',\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_author}')");
                $article_labels = array();
            } else {
                // we keep encountering the entry in feeds, so we need to
                // update date_updated column so that we don't get horrible
                // dupes when the entry gets purged and reinserted again e.g.
                // in the case of SLOW SLOW OMG SLOW updating feeds
                $base_entry_id = db_fetch_result($result, 0, "id");
                db_query("UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'");
                $article_labels = get_article_labels($base_entry_id, $owner_uid);
            }
            // now it should exist, if not - bad luck then
            $result = db_query("SELECT\n\t\t\t\t\t\tid,content_hash,no_orig_date,title,plugin_data,guid,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(date_updated,1,19) as date_updated,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(updated,1,19) as updated,\n\t\t\t\t\t\tnum_comments\n\t\t\t\t\tFROM\n\t\t\t\t\t\tttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}'");
            $entry_ref_id = 0;
            $entry_int_id = 0;
            if (db_num_rows($result) == 1) {
                _debug("base guid found, checking for user record", $debug_enabled);
                // this will be used below in update handler
                $orig_content_hash = db_fetch_result($result, 0, "content_hash");
                $orig_title = db_fetch_result($result, 0, "title");
                $orig_num_comments = db_fetch_result($result, 0, "num_comments");
                $orig_date_updated = strtotime(db_fetch_result($result, 0, "date_updated"));
                $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
                $ref_id = db_fetch_result($result, 0, "id");
                $entry_ref_id = $ref_id;
                /* $stored_guid = db_fetch_result($result, 0, "guid");
                					if ($stored_guid != $entry_guid_hashed) {
                						if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
                
                						db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
                							id = '$ref_id'");
                					} */
                // check for user post link to main table
                // do we allow duplicate posts with same GUID in different feeds?
                if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
                    $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)";
                } else {
                    $dupcheck_qpart = "";
                }
                /* Collect article tags here so we could filter by them: */
                $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags);
                if ($debug_enabled) {
                    _debug("article filters: ", $debug_enabled);
                    if (count($article_filters) != 0) {
                        print_r($article_filters);
                    }
                }
                if (find_article_filter($article_filters, "filter")) {
                    db_query("COMMIT");
                    // close transaction in progress
                    continue;
                }
                $score = calculate_article_score($article_filters);
                _debug("initial score: {$score}", $debug_enabled);
                $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}";
                //					if ($_REQUEST["xdebug"]) print "$query\n";
                $result = db_query($query);
                // okay it doesn't exist - create user entry
                if (db_num_rows($result) == 0) {
                    _debug("user record not found, creating...", $debug_enabled);
                    if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
                        $unread = 'true';
                        $last_read_qpart = 'NULL';
                    } else {
                        $unread = 'false';
                        $last_read_qpart = 'NOW()';
                    }
                    if (find_article_filter($article_filters, 'mark') || $score > 1000) {
                        $marked = 'true';
                    } else {
                        $marked = 'false';
                    }
                    if (find_article_filter($article_filters, 'publish')) {
                        $published = 'true';
                    } else {
                        $published = 'false';
                    }
                    // N-grams
                    if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
                        $result = db_query("SELECT COUNT(*) AS similar FROM\n\t\t\t\t\t\t\t\t\tttrss_entries,ttrss_user_entries\n\t\t\t\t\t\t\t\tWHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'\n\t\t\t\t\t\t\t\t\tAND similarity(title, '{$entry_title}') >= " . _NGRAM_TITLE_DUPLICATE_THRESHOLD . "\n\t\t\t\t\t\t\t\t\tAND owner_uid = {$owner_uid}");
                        $ngram_similar = db_fetch_result($result, 0, "similar");
                        _debug("N-gram similar results: {$ngram_similar}", $debug_enabled);
                        if ($ngram_similar > 0) {
                            $unread = 'false';
                        }
                    }
                    $last_marked = $marked == 'true' ? 'NOW()' : 'NULL';
                    $last_published = $published == 'true' ? 'NOW()' : 'NULL';
                    $result = db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid,\n\t\t\t\t\t\t\t\tlast_marked, last_published)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '',\n\t\t\t\t\t\t\t\t'', {$last_marked}, {$last_published})");
                    if (PUBSUBHUBBUB_HUB && $published == 'true') {
                        $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key(-2, false, $owner_uid);
                        $p = new Publisher(PUBSUBHUBBUB_HUB);
                        $pubsub_result = $p->publish_update($rss_link);
                    }
                    $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1");
                    if (db_num_rows($result) == 1) {
                        $entry_int_id = db_fetch_result($result, 0, "int_id");
                    }
                } else {
                    _debug("user record FOUND", $debug_enabled);
                    $entry_ref_id = db_fetch_result($result, 0, "ref_id");
                    $entry_int_id = db_fetch_result($result, 0, "int_id");
                }
                _debug("RID: {$entry_ref_id}, IID: {$entry_int_id}", $debug_enabled);
                $post_needs_update = false;
                $update_insignificant = false;
                if ($orig_num_comments != $num_comments) {
                    $post_needs_update = true;
                    $update_insignificant = true;
                }
                if ($entry_plugin_data != $orig_plugin_data) {
                    $post_needs_update = true;
                    $update_insignificant = true;
                }
                if ($content_hash != $orig_content_hash) {
                    $post_needs_update = true;
                    $update_insignificant = false;
                }
                if (db_escape_string($orig_title) != $entry_title) {
                    $post_needs_update = true;
                    $update_insignificant = false;
                }
                // if post needs update, update it and mark all user entries
                // linking to this post as updated
                if ($post_needs_update) {
                    if (defined('DAEMON_EXTENDED_DEBUG')) {
                        _debug("post {$entry_guid_hashed} needs update...", $debug_enabled);
                    }
                    //						print "<!-- post $orig_title needs update : $post_needs_update -->";
                    db_query("UPDATE ttrss_entries\n\t\t\t\t\t\t\tSET title = '{$entry_title}', content = '{$entry_content}',\n\t\t\t\t\t\t\t\tcontent_hash = '{$content_hash}',\n\t\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}'\n\t\t\t\t\t\t\tWHERE id = '{$ref_id}'");
                    if (!$update_insignificant) {
                        if ($mark_unread_on_update) {
                            db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'");
                        }
                    }
                }
            }
            db_query("COMMIT");
            _debug("assigning labels...", $debug_enabled);
            assign_article_to_label_filters($entry_ref_id, $article_filters, $owner_uid, $article_labels);
            _debug("looking for enclosures...", $debug_enabled);
            // enclosures
            $enclosures = array();
            $encs = $item->get_enclosures();
            if (is_array($encs)) {
                foreach ($encs as $e) {
                    $e_item = array($e->link, $e->type, $e->length);
                    array_push($enclosures, $e_item);
                }
            }
            if ($debug_enabled) {
                _debug("article enclosures:", $debug_enabled);
                print_r($enclosures);
            }
            db_query("BEGIN");
            foreach ($enclosures as $enc) {
                $enc_url = db_escape_string($enc[0]);
                $enc_type = db_escape_string($enc[1]);
                $enc_dur = db_escape_string($enc[2]);
                $result = db_query("SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'");
                if (db_num_rows($result) == 0) {
                    db_query("INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '', '{$enc_dur}', '{$entry_ref_id}')");
                }
            }
            db_query("COMMIT");
            // check for manual tags (we have to do it here since they're loaded from filters)
            foreach ($article_filters as $f) {
                if ($f["type"] == "tag") {
                    $manual_tags = trim_array(explode(",", $f["param"]));
                    foreach ($manual_tags as $tag) {
                        if (tag_is_valid($tag)) {
                            array_push($entry_tags, $tag);
                        }
                    }
                }
            }
            // Skip boring tags
            $boring_tags = trim_array(explode(",", mb_strtolower(get_pref('BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
            $filtered_tags = array();
            $tags_to_cache = array();
            if ($entry_tags && is_array($entry_tags)) {
                foreach ($entry_tags as $tag) {
                    if (array_search($tag, $boring_tags) === false) {
                        array_push($filtered_tags, $tag);
                    }
                }
            }
            $filtered_tags = array_unique($filtered_tags);
            if ($debug_enabled) {
                _debug("filtered article tags:", $debug_enabled);
                print_r($filtered_tags);
            }
            // Save article tags in the database
            if (count($filtered_tags) > 0) {
                db_query("BEGIN");
                foreach ($filtered_tags as $tag) {
                    $tag = sanitize_tag($tag);
                    $tag = db_escape_string($tag);
                    if (!tag_is_valid($tag)) {
                        continue;
                    }
                    $result = db_query("SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1");
                    if ($result && db_num_rows($result) == 0) {
                        db_query("INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')");
                    }
                    array_push($tags_to_cache, $tag);
                }
                /* update the cache */
                $tags_to_cache = array_unique($tags_to_cache);
                $tags_str = db_escape_string(join(",", $tags_to_cache));
                db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}");
                db_query("COMMIT");
            }
            if (get_pref("AUTO_ASSIGN_LABELS", $owner_uid, false)) {
                _debug("auto-assigning labels...", $debug_enabled);
                foreach ($labels as $label) {
                    $caption = preg_quote($label["caption"]);
                    if ($caption && preg_match("/\\b{$caption}\\b/i", "{$tags_str} " . strip_tags($entry_content) . " {$entry_title}")) {
                        if (!labels_contains_caption($article_labels, $caption)) {
                            label_add_article($entry_ref_id, $caption, $owner_uid);
                        }
                    }
                }
            }
            _debug("article processed", $debug_enabled);
        }
        _debug("purging feed...", $debug_enabled);
        purge_feed($feed, 0, $debug_enabled);
        db_query("UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
        //			db_query("COMMIT");
    } else {
        $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
        _debug("error fetching feed: {$error_msg}", $debug_enabled);
        db_query("UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
    }
    unset($rss);
    _debug("done", $debug_enabled);
}
Ejemplo n.º 16
0
<?php
include dirname(__FILE__) . "/../../../include/db.php";
include dirname(__FILE__) . "/../../../include/authenticate.php";
include dirname(__FILE__) . "/../../../include/general.php";

$field=getvalescaped("field","");
$keyword=getvalescaped("term","");

$fielddata=get_resource_type_field($field);
$readonly=getval("readonly","");
?>[ <?php

# Return matches
$first=true;
$exactmatch=false;
$options=trim_array(explode(",",$fielddata["options"]));
for ($m=0;$m<count($options);$m++)
	{
	$trans=i18n_get_translated($options[$m]);
	if ($trans!="" && substr(strtolower($trans),0,strlen($keyword))==strtolower($keyword))
		{
		if (!$first) { ?>, <?php }
		$first=false;
		
		if (strtolower($trans)==strtolower($keyword)) {$exactmatch=true;}
		?>"<?php echo $trans ?>"<?php
		}
	}
	
if (!$exactmatch && !$readonly)
	{
Ejemplo n.º 17
0
if (!hook("customchkboxes")) {
    # Translate all options
    $options = trim_array(explode(",", $field["options"]));
    $option_trans = array();
    $option_trans_simple = array();
    for ($m = 0; $m < count($options); $m++) {
        $trans = i18n_get_translated($options[$m]);
        $option_trans[$options[$m]] = $trans;
        $option_trans_simple[] = $trans;
    }
    if ($auto_order_checkbox) {
        natsort($option_trans);
    }
    $options = array_keys($option_trans);
    # Set the options array to the keys, so it is now effectively sorted by translated string
    $set = trim_array(explode(",", $value));
    $wrap = 0;
    $l = average_length($option_trans_simple);
    $cols = 10;
    if ($l > 5) {
        $cols = 6;
    }
    if ($l > 10) {
        $cols = 4;
    }
    if ($l > 15) {
        $cols = 3;
    }
    if ($l > 25) {
        $cols = 2;
    }
Ejemplo n.º 18
0
function search_form_to_search_query($fields, $fromsearchbar = false)
{
    # Take the data in the the posted search form that contained $fields, and assemble
    # a search query string that can be used for a standard search.
    #
    # This is used to take the advanced search form and assemble it into a search query.
    global $auto_order_checkbox, $checkbox_and;
    $search = "";
    if (getval("year", "") != "") {
        if ($search != "") {
            $search .= ", ";
        }
        $search .= "year:" . getval("year", "");
    }
    if (getval("month", "") != "") {
        if ($search != "") {
            $search .= ", ";
        }
        $search .= "month:" . getval("month", "");
    }
    if (getval("day", "") != "") {
        if ($search != "") {
            $search .= ", ";
        }
        $search .= "day:" . getval("day", "");
    }
    if (getval("allfields", "") != "") {
        if ($search != "") {
            $search .= ", ";
        }
        $search .= join(", ", explode(" ", getvalescaped("allfields", "")));
        # prepend 'all fields' option
    }
    if (getval("resourceids", "") != "") {
        $listsql = "!list" . join(":", trim_array(split_keywords(getvalescaped("resourceids", ""))));
        $search = $listsql . " " . $search;
    }
    for ($n = 0; $n < count($fields); $n++) {
        switch ($fields[$n]["type"]) {
            case 0:
                # -------- Text boxes
            # -------- Text boxes
            case 1:
            case 5:
                $name = "field_" . $fields[$n]["ref"];
                $value = getvalescaped($name, "");
                if ($value != "") {
                    $vs = split_keywords($value);
                    for ($m = 0; $m < count($vs); $m++) {
                        if ($search != "") {
                            $search .= ", ";
                        }
                        $search .= $fields[$n]["name"] . ":" . strtolower($vs[$m]);
                    }
                }
                break;
            case 2:
                # -------- Dropdowns / check lists
            # -------- Dropdowns / check lists
            case 3:
                if ($fields[$n]["display_as_dropdown"]) {
                    # Process dropdown box
                    $name = "field_" . $fields[$n]["ref"];
                    $value = getvalescaped($name, "");
                    if ($value != "") {
                        /*
                        $vs=split_keywords($value);
                        for ($m=0;$m<count($vs);$m++)
                        	{
                        	if ($search!="") {$search.=", ";}
                        	$search.=$fields[$n]["name"] . ":" . strtolower($vs[$m]);
                        	}
                        */
                        if ($search != "") {
                            $search .= ", ";
                        }
                        $search .= $fields[$n]["name"] . ":" . $value;
                    }
                } else {
                    # Process checkbox list
                    $options = trim_array(explode(",", $fields[$n]["options"]));
                    $p = "";
                    $c = 0;
                    for ($m = 0; $m < count($options); $m++) {
                        $name = $fields[$n]["ref"] . "_" . md5($options[$m]);
                        $value = getvalescaped($name, "");
                        if ($value == "yes") {
                            $c++;
                            if ($p != "") {
                                $p .= ";";
                            }
                            $p .= strtolower(i18n_get_translated($options[$m]));
                        }
                    }
                    if ($c == count($options) && !$checkbox_and) {
                        # all options ticked - omit from the search (unless using AND matching)
                        $p = "";
                    }
                    if ($p != "") {
                        if ($search != "") {
                            $search .= ", ";
                        }
                        $search .= $fields[$n]["name"] . ":" . $p;
                    }
                }
                break;
            case 4:
            case 6:
                $name = "field_" . $fields[$n]["ref"];
                $datepart = "";
                if (getval($name . "_year", "") != "") {
                    $datepart .= getval($name . "_year", "");
                    if (getval($name . "_month", "") != "") {
                        $datepart .= "-" . getval($name . "_month", "");
                        if (getval($name . "_day", "") != "") {
                            $datepart .= "-" . getval($name . "_day", "");
                        }
                    }
                }
                if ($datepart != "") {
                    if ($search != "") {
                        $search .= ", ";
                    }
                    $search .= $fields[$n]["name"] . ":" . $datepart;
                }
                break;
            case 7:
            case 9:
                # -------- Category tree and dynamic keywords
                $name = "field_" . $fields[$n]["ref"];
                $value = getvalescaped($name, "");
                $selected = trim_array(explode(",", $value));
                $p = "";
                for ($m = 0; $m < count($selected); $m++) {
                    if ($selected[$m] != "") {
                        if ($p != "") {
                            $p .= ";";
                        }
                        $p .= $selected[$m];
                    }
                    # Resolve keywords to make sure that the value has been indexed prior to including in the search string.
                    $keywords = split_keywords($selected[$m]);
                    foreach ($keywords as $keyword) {
                        resolve_keyword($keyword, true);
                    }
                }
                if ($p != "") {
                    if ($search != "") {
                        $search .= ", ";
                    }
                    $search .= $fields[$n]["name"] . ":" . $p;
                }
                break;
        }
    }
    return $search;
}
        if (substr($key, 0, 11) == "permission_") {
            # Found a permisison.
            $reverse = $value == "reverse";
            $key = substr($key, 11);
            if (!$reverse && getval("checked_" . $key, "") != "" || $reverse && !getval("checked_" . $key, "") != "") {
                $perms[] = urldecode($key);
            }
        }
    }
    if (getval("other", "") != "") {
        $perms[] = getvalescaped("other", "");
    }
    sql_query("update usergroup set permissions='" . join(",", $perms) . "' where ref='{$ref}'");
}
$group = get_usergroup($ref);
$permissions = trim_array(explode(",", $group["permissions"]));
$permissions_done = array();
function DrawOption($permission, $description, $reverse = false, $reload = false)
{
    global $permissions, $permissions_done;
    $checked = in_array($permission, $permissions);
    if ($reverse) {
        $checked = !$checked;
    }
    ?>
	<input type="hidden" name="permission_<?php 
    echo urlencode($permission);
    ?>
" value="<?php 
    echo $reverse ? "reverse" : "normal";
    ?>
function save_proposed_changes($ref)
{
    global $userref, $auto_order_checkbox, $multilingual_text_fields, $languages, $language;
    # Loop through the field data and save (if necessary)
    $errors = array();
    $fields = get_resource_field_data($ref, false);
    $resource_data = get_resource_data($ref);
    for ($n = 0; $n < count($fields); $n++) {
        if ($fields[$n]["type"] == 2) {
            # construct the value from the ticked boxes
            $val = ",";
            # Note: it seems wrong to start with a comma, but this ensures it is treated as a comma separated list by split_keywords(), so if just one item is selected it still does individual word adding, so 'South Asia' is split to 'South Asia','South','Asia'.
            $options = trim_array(explode(",", $fields[$n]["options"]));
            for ($m = 0; $m < count($options); $m++) {
                $name = $fields[$n]["ref"] . "_" . md5($options[$m]);
                if (getval($name, "") == "yes") {
                    if ($val != ",") {
                        $val .= ",";
                    }
                    $val .= $options[$m];
                }
            }
        } elseif ($fields[$n]["type"] == 4 || $fields[$n]["type"] == 6 || $fields[$n]["type"] == 10) {
            # date type, construct the value from the date/time dropdowns
            $val = sprintf("%04d", getvalescaped("field_" . $fields[$n]["ref"] . "-y", ""));
            if ((int) $val <= 0) {
                $val = "";
            } elseif (($field = getvalescaped("field_" . $fields[$n]["ref"] . "-m", "")) != "") {
                $val .= "-" . $field;
                if (($field = getvalescaped("field_" . $fields[$n]["ref"] . "-d", "")) != "") {
                    $val .= "-" . $field;
                    if (($field = getval("field_" . $fields[$n]["ref"] . "-h", "")) != "") {
                        $val .= " " . $field . ":";
                        if (($field = getvalescaped("field_" . $fields[$n]["ref"] . "-i", "")) != "") {
                            $val .= $field;
                        } else {
                            $val .= "00";
                        }
                    }
                }
            }
        } elseif ($multilingual_text_fields && ($fields[$n]["type"] == 0 || $fields[$n]["type"] == 1 || $fields[$n]["type"] == 5)) {
            # Construct a multilingual string from the submitted translations
            $val = getvalescaped("field_" . $fields[$n]["ref"], "");
            $val = "~" . $language . ":" . $val;
            reset($languages);
            foreach ($languages as $langkey => $langname) {
                if ($language != $langkey) {
                    $val .= "~" . $langkey . ":" . getvalescaped("multilingual_" . $n . "_" . $langkey, "");
                }
            }
        } elseif ($fields[$n]["type"] == 3) {
            $val = getvalescaped("field_" . $fields[$n]["ref"], "");
            // if it doesn't already start with a comma, add one
            if (substr($val, 0, 1) != ',') {
                $val = ',' . $val;
            }
        } else {
            # Set the value exactly as sent.
            $val = getvalescaped("field_" . $fields[$n]["ref"], "");
        }
        # Check for regular expression match
        if (trim(strlen($fields[$n]["regexp_filter"])) >= 1 && strlen($val) > 0) {
            if (preg_match("#^" . $fields[$n]["regexp_filter"] . "\$#", $val, $matches) <= 0) {
                global $lang;
                debug($lang["information-regexp_fail"] . ": -" . "reg exp: " . $fields[$n]["regexp_filter"] . ". Value passed: " . $val);
                if (getval("autosave", "") != "") {
                    exit;
                }
                $errors[$fields[$n]["ref"]] = $lang["information-regexp_fail"] . " : " . $val;
                continue;
            }
        }
        $error = hook("additionalvalcheck", "all", array($fields, $fields[$n]));
        if ($error) {
            global $lang;
            $errors[$fields[$n]["ref"]] = $error;
            continue;
        }
        if (str_replace("\r\n", "\n", $fields[$n]["value"]) !== str_replace("\r\n", "\n", unescape($val))) {
            # This value is different from the value we have on record.
            # Add this to the proposed changes table for the user
            sql_query("insert into propose_changes_data(resource,user,resource_type_field,value) values('{$ref}','{$userref}','" . $fields[$n]["ref"] . "','" . escape_check($val) . "')");
        }
    }
    return true;
}
 $oCkbConfirmed = new cHTMLCheckbox("confirmed", "1");
 $oCkbConfirmed->setChecked($recipient->get("confirmed"));
 $oCkbDeactivated = new cHTMLCheckbox("deactivated", "1");
 $oCkbDeactivated->setChecked($recipient->get("deactivated"));
 $oSelNewsType = new cHTMLSelectElement("newstype");
 $oOption = new cHTMLOptionElement(i18n("Text only", $plugin_name), "0");
 $oSelNewsType->addOptionElement(0, $oOption);
 $oOption = new cHTMLOptionElement(i18n("HTML and text", $plugin_name), "1");
 $oSelNewsType->addOptionElement(1, $oOption);
 $oSelNewsType->setDefault($recipient->get("news_type"));
 $oForm->add(i18n("Name", $plugin_name), $oTxtName->render());
 $oForm->add(i18n("E-Mail", $plugin_name), $oTxtEMail->render());
 $oForm->add(i18n("Confirmed", $plugin_name), $oCkbConfirmed->toHTML(false) . " (" . $recipient->get("confirmeddate") . ")");
 $oForm->add(i18n("Deactivated", $plugin_name), $oCkbDeactivated->toHTML(false));
 $oForm->add(i18n("Message type", $plugin_name), $oSelNewsType->render());
 $aPluginOrder = trim_array(explode(",", getSystemProperty("plugin", "recipients-pluginorder")));
 // Check out if there are any plugins
 if (is_array($aPluginOrder)) {
     foreach ($aPluginOrder as $sPlugin) {
         if (function_exists("recipients_" . $sPlugin . "_getTitle") && function_exists("recipients_" . $sPlugin . "_display")) {
             $aPluginTitle = call_user_func("recipients_" . $sPlugin . "_getTitle");
             $aPluginDisplay = call_user_func("recipients_" . $sPlugin . "_display", $recipient);
             if (is_array($aPluginTitle) && is_array($aPluginDisplay)) {
                 foreach ($aPluginTitle as $sKey => $sValue) {
                     $oForm->add($sValue, $aPluginDisplay[$sKey]);
                 }
             } else {
                 if (is_array($aPluginTitle) || is_array($aPluginDisplay)) {
                     $oForm->add(i18n("WARNING", $plugin_name), sprintf(i18n("The plugin %s delivered an array for the displayed titles, but did not return an array for the contents.", $plugin_name), $sPlugin));
                 } else {
                     $oForm->add($aPluginTitle, $aPluginDisplay);
 function email_collection($colrefs, $collectionname, $fromusername, $userlist, $message, $feedback, $access = -1, $expires = "", $useremail = "", $from_name = "", $cc = "")
 {
     # Attempt to resolve all users in the string $userlist to user references.
     # Add $collection to these user's 'My Collections' page
     # Send them an e-mail linking to this collection
     #  handle multiple collections (comma seperated list)
     global $baseurl, $email_from, $applicationname, $lang, $userref, $email_multi_collections;
     if ($useremail == "") {
         $useremail = $email_from;
     }
     if (trim($userlist) == "") {
         return $lang["mustspecifyoneusername"];
     }
     $userlist = resolve_userlist_groups($userlist);
     $ulist = trim_array(explode(",", $userlist));
     $emails = array();
     $key_required = array();
     if ($feedback) {
         $feedback = 1;
     } else {
         $feedback = 0;
     }
     $reflist = trim_array(explode(",", $colrefs));
     $emails_keys = resolve_user_emails($ulist);
     $emails = $emails_keys['emails'];
     $key_required = $emails_keys['key_required'];
     # Add the collection(s) to the user's My Collections page
     $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')");
     if (count($urefs) > 0) {
         #�Delete any existing collection entries
         sql_query("delete from user_collection where collection in ('" . join("','", $reflist) . "') and user in ('" . join("','", $urefs) . "')");
         # Insert new user_collection row(s)
         #loop through the collections
         for ($nx1 = 0; $nx1 < count($reflist); $nx1++) {
             #loop through the users
             for ($nx2 = 0; $nx2 < count($urefs); $nx2++) {
                 sql_query("insert into user_collection(collection,user,request_feedback) values ({$reflist[$nx1]}, {$urefs[$nx2]}, {$feedback} )");
                 #log this
                 collection_log($reflist[$nx1], "S", 0, sql_value("select username as value from user where ref = {$urefs[$nx2]}", ""));
             }
         }
     }
     # Send an e-mail to each resolved user
     # htmlbreak is for composing list
     $htmlbreak = "";
     global $use_phpmailer;
     if ($use_phpmailer) {
         $htmlbreak = "<br><br>";
         $htmlbreaksingle = "<br>";
     }
     if ($fromusername == "") {
         $fromusername = $applicationname;
     }
     // fromusername is used for describing the sender's name inside the email
     if ($from_name == "") {
         $from_name = $applicationname;
     }
     // from_name is for the email headers, and needs to match the email address (app name or user name)
     $templatevars['message'] = str_replace(array("\\n", "\\r", "\\"), array("\n", "\r", ""), $message);
     if (trim($templatevars['message']) == "") {
         $templatevars['message'] = $lang['nomessage'];
     }
     $templatevars['fromusername'] = $fromusername;
     $templatevars['from_name'] = $from_name;
     if (count($reflist) > 1) {
         $subject = $applicationname . ": " . $lang['mycollections'];
     } else {
         $subject = $applicationname . ": " . $collectionname;
     }
     if ($fromusername == "") {
         $fromusername = $applicationname;
     }
     ##  loop through recipients
     for ($nx1 = 0; $nx1 < count($emails); $nx1++) {
         ## loop through collections
         $list = "";
         $list2 = "";
         for ($nx2 = 0; $nx2 < count($reflist); $nx2++) {
             $url = "";
             $key = "";
             $emailcollectionmessageexternal = false;
             # Do we need to add an external access key for this user (e-mail specified rather than username)?
             if ($key_required[$nx1]) {
                 $k = generate_collection_access_key($reflist[$nx2], $feedback, $emails[$nx1], $access, $expires);
                 $key = "&k=" . $k;
                 $emailcollectionmessageexternal = true;
             }
             $url = $baseurl . "/?c=" . $reflist[$nx2] . $key;
             $collection_name = "";
             $collection_name = sql_value("select name value from collection where ref='{$reflist[$nx2]}'", "{$reflist[$nx2]}");
             if ($use_phpmailer) {
                 $link = "<a href=\"{$url}\">{$collection_name}</a>";
                 $list .= $htmlbreak . $link;
                 // alternate list style
                 $list2 .= $htmlbreak . $collection_name . ' -' . $htmlbreaksingle . $url;
                 $templatevars['list2'] = $list2;
             } else {
                 $list .= $htmlbreak . $url;
             }
             #log this
             collection_log($reflist[$nx2], "E", 0, $emails[$nx1]);
         }
         //$list.=$htmlbreak;
         $templatevars['list'] = $list;
         $templatevars['from_name'] = $from_name;
         if ($emailcollectionmessageexternal) {
             $template = "emailcollectionexternal";
         } else {
             $template = "emailcollection";
         }
         $body = $templatevars['fromusername'] . " " . ($emailcollectionmessageexternal ? $lang["emailcollectionmessageexternal"] : $lang["emailcollectionmessage"]) . "\n\n" . $templatevars['message'] . "\n\n" . $lang["clicklinkviewcollection"] . "\n\n" . $templatevars['list'];
         send_mail($emails[$nx1], $subject, $body, $fromusername, $useremail, $template, $templatevars, $from_name, $cc);
     }
     # Return an empty string (all OK).
     return "";
 }
Ejemplo n.º 23
0
function HookLicensemanagerViewCustompanels()
{
    global $lang, $baseurl_short, $ref, $edit_access, $k;
    if ($k != "") {
        return false;
    }
    $licenses = sql_query("select ref,outbound,holder,license_usage,description,expires from resource_license where resource='{$ref}' order by ref");
    ?>
    <!-- Begin Geolocation Section -->
    <div class="RecordBox">
    <div class="RecordPanel">
    <div class="Title"><?php 
    echo $lang["license_management"];
    ?>
</div>

    <?php 
    if ($edit_access) {
        ?>
    
    <p>&gt;&nbsp;<a href="<?php 
        echo $baseurl_short;
        ?>
plugins/licensemanager/pages/edit.php?ref=new&resource=<?php 
        echo $ref;
        ?>
" onClick="return CentralSpaceLoad(this,true);"><?php 
        echo $lang["new_license"];
        ?>
</a></p>	
    <?php 
    }
    ?>
   
	<?php 
    if (count($licenses) > 0) {
        ?>
		<div class="Listview">
		<table border="0" cellspacing="0" cellpadding="0" class="ListviewStyle">
		<tr class="ListviewTitleStyle">
		<td><?php 
        echo $lang["license_id"];
        ?>
</a></td>
		<td><?php 
        echo $lang["type"];
        ?>
</a></td>
		<td><?php 
        echo $lang["licensor_licensee"];
        ?>
</a></td>
		<td><?php 
        echo $lang["indicateusagemedium"];
        ?>
</a></td>
		<td><?php 
        echo $lang["description"];
        ?>
</a></td>
		<td><?php 
        echo $lang["fieldtitle-expiry_date"];
        ?>
</a></td>

		<?php 
        if ($edit_access) {
            ?>
		<td><div class="ListTools"><?php 
            echo $lang["tools"];
            ?>
</div></td>
		<?php 
        }
        ?>
		
		</tr>
	
		<?php 
        foreach ($licenses as $license) {
            $license_usage_mediums = trim_array(explode(", ", $license["license_usage"]));
            $translated_mediums = "";
            ?>
			<tr>
			<td><?php 
            echo $license["ref"];
            ?>
</td>
			<td><?php 
            echo $license["outbound"] ? $lang["outbound"] : $lang["inbound"];
            ?>
</td>
			<td><?php 
            echo $license["holder"];
            ?>
</td>
			<td><?php 
            foreach ($license_usage_mediums as $medium) {
                $translated_mediums = $translated_mediums . lang_or_i18n_get_translated($medium, "license_usage-") . ", ";
            }
            $translated_mediums = substr($translated_mediums, 0, -2);
            # Remove the last ", "
            echo $translated_mediums;
            ?>
			</td>
			<td><?php 
            echo $license["description"];
            ?>
</td>
			<td><?php 
            echo nicedate($license["expires"]);
            ?>
</td>
		
			<?php 
            if ($edit_access) {
                ?>
			<td><div class="ListTools">
			<a href="<?php 
                echo $baseurl_short;
                ?>
plugins/licensemanager/pages/edit.php?ref=<?php 
                echo $license["ref"];
                ?>
&resource=<?php 
                echo $ref;
                ?>
" onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php 
                echo $lang["action-edit"];
                ?>
</a>
			<a href="<?php 
                echo $baseurl_short;
                ?>
plugins/licensemanager/pages/delete.php?ref=<?php 
                echo $license["ref"];
                ?>
&resource=<?php 
                echo $ref;
                ?>
" onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php 
                echo $lang["action-delete"];
                ?>
</a>
			</div></td>
			<?php 
            }
            ?>
						
			</tr>
			<?php 
        }
        ?>
		
		</table>
		</div>
	<?php 
    }
    ?>

    
    </div>
    <div class="PanelShadow"></div>
    </div>
    <?php 
    return false;
    # Allow further custom panels
}
Ejemplo n.º 24
0
                $set_fields[$s[0]] = $s[1];
            }
            if (!in_array($s[0], $simple_fields)) {
                $simple[] = trim($keywords[$n]);
            }
        } else {
            # Plain text (non field) search.
            $simple[] = trim($keywords[$n]);
        }
    }
}
# Set the text search box to the stripped value.
if ($quoted_string) {
    $quicksearch = join(" ", trim_array($simple));
} else {
    $quicksearch = join(", ", trim_array($simple));
    $quicksearch = str_replace(",-", " -", $quicksearch);
}
# Add the quotes back, if a quoted string
if ($quoted_string) {
    $quicksearch = "\"" . trim($quicksearch) . "\"";
}
# Set the predefined date fields
$found_year = "";
if (isset($set_fields["year"])) {
    $found_year = $set_fields["year"];
}
$found_month = "";
if (isset($set_fields["month"])) {
    $found_month = $set_fields["month"];
}
 function email_collection($colrefs, $collectionname, $fromusername, $userlist, $message, $feedback, $access = -1, $expires = "", $useremail = "", $from_name = "", $cc = "", $themeshare = false, $themename = "", $themeurlsuffix = "", $list_recipients = false, $add_internal_access = false, $group = "")
 {
     # Attempt to resolve all users in the string $userlist to user references.
     # Add $collection to these user's 'My Collections' page
     # Send them an e-mail linking to this collection
     #  handle multiple collections (comma seperated list)
     global $baseurl, $email_from, $applicationname, $lang, $userref, $email_multi_collections, $usergroup, $attach_user_smart_groups;
     if ($useremail == "") {
         $useremail = $email_from;
     }
     if ($group == "") {
         $group = $usergroup;
     }
     if (trim($userlist) == "") {
         return $lang["mustspecifyoneusername"];
     }
     $userlist = resolve_userlist_groups($userlist);
     if ($attach_user_smart_groups && strpos($userlist, $lang["groupsmart"] . ": ") !== false) {
         $groups_users = resolve_userlist_groups_smart($userlist, true);
         if ($groups_users != '') {
             if ($userlist != "") {
                 $userlist = remove_groups_smart_from_userlist($userlist);
                 if ($userlist != "") {
                     $userlist .= ",";
                 }
             }
             $userlist .= $groups_users;
         }
     }
     $ulist = trim_array(explode(",", $userlist));
     $emails = array();
     $key_required = array();
     if ($feedback) {
         $feedback = 1;
     } else {
         $feedback = 0;
     }
     $reflist = trim_array(explode(",", $colrefs));
     $emails_keys = resolve_user_emails($ulist);
     $emails = $emails_keys['emails'];
     $key_required = $emails_keys['key_required'];
     # Add the collection(s) to the user's My Collections page
     $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')");
     if (count($urefs) > 0) {
         # Delete any existing collection entries
         sql_query("delete from user_collection where collection in ('" . join("','", $reflist) . "') and user in ('" . join("','", $urefs) . "')");
         # Insert new user_collection row(s)
         #loop through the collections
         for ($nx1 = 0; $nx1 < count($reflist); $nx1++) {
             #loop through the users
             for ($nx2 = 0; $nx2 < count($urefs); $nx2++) {
                 sql_query("insert into user_collection(collection,user,request_feedback) values ({$reflist[$nx1]}, {$urefs[$nx2]}, {$feedback} )");
                 if ($add_internal_access) {
                     foreach (get_collection_resources($reflist[$nx1]) as $resource) {
                         if (get_edit_access($resource)) {
                             open_access_to_user($urefs[$nx2], $resource, $expires);
                         }
                     }
                 }
                 #log this
                 collection_log($reflist[$nx1], "S", 0, sql_value("select username as value from user where ref = {$urefs[$nx2]}", ""));
             }
         }
     }
     # Send an e-mail to each resolved user
     # htmlbreak is for composing list
     $htmlbreak = "\r\n";
     global $use_phpmailer;
     if ($use_phpmailer) {
         $htmlbreak = "<br><br>";
         $htmlbreaksingle = "<br>";
     }
     if ($fromusername == "") {
         $fromusername = $applicationname;
     }
     // fromusername is used for describing the sender's name inside the email
     if ($from_name == "") {
         $from_name = $applicationname;
     }
     // from_name is for the email headers, and needs to match the email address (app name or user name)
     $templatevars['message'] = str_replace(array("\\n", "\\r", "\\"), array("\n", "\r", ""), $message);
     if (trim($templatevars['message']) == "") {
         $templatevars['message'] = $lang['nomessage'];
     }
     $templatevars['fromusername'] = $fromusername;
     $templatevars['from_name'] = $from_name;
     if (count($reflist) > 1) {
         $subject = $applicationname . ": " . $lang['mycollections'];
     } else {
         $subject = $applicationname . ": " . $collectionname;
     }
     if ($fromusername == "") {
         $fromusername = $applicationname;
     }
     $externalmessage = $lang["emailcollectionmessageexternal"];
     $internalmessage = $lang["emailcollectionmessage"];
     $viewlinktext = $lang["clicklinkviewcollection"];
     if ($themeshare) {
         $externalmessage = $lang["emailthemecollectionmessageexternal"];
         $internalmessage = $lang["emailthememessage"];
         $viewlinktext = $lang["clicklinkviewcollections"];
     }
     ##  loop through recipients
     for ($nx1 = 0; $nx1 < count($emails); $nx1++) {
         ## loop through collections
         $list = "";
         $list2 = "";
         $origviewlinktext = $viewlinktext;
         // Save this text as we may change it for internal theme shares for this user
         if ($themeshare && !$key_required[$nx1]) {
             $url = "";
             $subject = $applicationname . ": " . $themename;
             $url = $baseurl . "/pages/themes.php" . $themeurlsuffix;
             $viewlinktext = $lang["clicklinkviewthemes"];
             $emailcollectionmessageexternal = false;
             if ($use_phpmailer) {
                 $link = "<a href=\"{$url}\">" . $themename . "</a>";
                 $list .= $htmlbreak . $link;
                 // alternate list style
                 $list2 .= $htmlbreak . $themename . ' -' . $htmlbreaksingle . $url;
                 $templatevars['list2'] = $list2;
             } else {
                 $list .= $htmlbreak . $url;
             }
             for ($nx2 = 0; $nx2 < count($reflist); $nx2++) {
                 #log this
                 collection_log($reflist[$nx2], "E", 0, $emails[$nx1]);
             }
         } else {
             for ($nx2 = 0; $nx2 < count($reflist); $nx2++) {
                 $url = "";
                 $key = "";
                 $emailcollectionmessageexternal = false;
                 # Do we need to add an external access key for this user (e-mail specified rather than username)?
                 if ($key_required[$nx1]) {
                     $k = generate_collection_access_key($reflist[$nx2], $feedback, $emails[$nx1], $access, $expires, $group);
                     $key = "&k=" . $k;
                     $emailcollectionmessageexternal = true;
                 }
                 $url = $baseurl . "/?c=" . $reflist[$nx2] . $key;
                 $collection = array();
                 $collection = sql_query("select name,savedsearch from collection where ref='{$reflist[$nx2]}'");
                 if ($collection[0]["name"] != "") {
                     $collection_name = i18n_get_collection_name($collection[0]);
                 } else {
                     $collection_name = $reflist[$nx2];
                 }
                 if ($use_phpmailer) {
                     $link = "<a href=\"{$url}\">{$collection_name}</a>";
                     $list .= $htmlbreak . $link;
                     // alternate list style
                     $list2 .= $htmlbreak . $collection_name . ' -' . $htmlbreaksingle . $url;
                     $templatevars['list2'] = $list2;
                 } else {
                     $list .= $htmlbreak . $collection_name . $htmlbreak . $url . $htmlbreak;
                 }
                 #log this
                 collection_log($reflist[$nx2], "E", 0, $emails[$nx1]);
             }
         }
         //$list.=$htmlbreak;
         $templatevars['list'] = $list;
         $templatevars['from_name'] = $from_name;
         if (isset($k)) {
             if ($expires == "") {
                 $templatevars['expires_date'] = $lang["email_link_expires_never"];
                 $templatevars['expires_days'] = $lang["email_link_expires_never"];
             } else {
                 $day_count = round((strtotime($expires) - strtotime('now')) / (60 * 60 * 24));
                 $templatevars['expires_date'] = $lang['email_link_expires_date'] . nicedate($expires);
                 $templatevars['expires_days'] = $lang['email_link_expires_days'] . $day_count;
                 if ($day_count > 1) {
                     $templatevars['expires_days'] .= " " . $lang['expire_days'] . ".";
                 } else {
                     $templatevars['expires_days'] .= " " . $lang['expire_day'] . ".";
                 }
             }
         } else {
             # Set empty expiration tempaltevars
             $templatevars['expires_date'] = '';
             $templatevars['expires_days'] = '';
         }
         if ($emailcollectionmessageexternal) {
             $template = $themeshare ? "emailthemeexternal" : "emailcollectionexternal";
         } else {
             $template = $themeshare ? "emailtheme" : "emailcollection";
         }
         if (count($emails > 1) && $list_recipients === true) {
             $body = $lang["list-recipients"] . "\n" . implode("\n", $emails) . "\n\n";
             $templatevars['list-recipients'] = $lang["list-recipients"] . "\n" . implode("\n", $emails) . "\n\n";
         } else {
             $body = "";
         }
         $body .= $templatevars['fromusername'] . " " . ($emailcollectionmessageexternal ? $externalmessage : $internalmessage) . "\n\n" . $templatevars['message'] . "\n\n" . $viewlinktext . "\n\n" . $templatevars['list'];
         #exit ($body . "<br>" . $viewlinktext);
         send_mail($emails[$nx1], $subject, $body, $fromusername, $useremail, $template, $templatevars, $from_name, $cc);
         $viewlinktext = $origviewlinktext;
     }
     hook("additional_email_collection", "", array($colrefs, $collectionname, $fromusername, $userlist, $message, $feedback, $access, $expires, $useremail, $from_name, $cc, $themeshare, $themename, $themeurlsuffix, $template, $templatevars));
     # Return an empty string (all OK).
     return "";
 }
Ejemplo n.º 26
0
 /**
  * Return only the objects with these ids.
  * @param string $ids Comma-separated list of integers.
  * @param boolean $invert_logic If true, returns all objects NOT matching the query.
  * @param string $method_name Name of the method to call to retrieve objects.
  * @return object[]
  */
 protected function _objects_at_ids($ids, $invert_logic, $method_name)
 {
     if (!is_array($ids)) {
         $ids = trim_array(explode(',', $ids));
     }
     if (sizeof($ids) > 0) {
         if (!$invert_logic && isset($this->_objects)) {
             // objects have already been calculated
             $this->_system_call = true;
             $indexed_objs = $this->indexed_objects();
             $this->_system_call = false;
             /* loop through all the ids, getting them out of cache. As soon as one
              * is not in the cache, erase the whole result and go to the database in
              * the next step. Otherwise, all the objects were found without hitting
              * the cache.
              */
             $Result = null;
             foreach ($ids as $id) {
                 if (isset($indexed_objs[$id])) {
                     $Result[] = $indexed_objs[$id];
                 } else {
                     $Result = null;
                     break;
                 }
             }
         }
         if ((!isset($Result) || !sizeof($Result)) && sizeof($ids)) {
             $ids = join(', ', $ids);
             if ($ids) {
                 if ($invert_logic) {
                     $this->_start_system_call('NOT (' . $this->alias . '.' . $this->id . ' IN (' . $ids . '))');
                 } else {
                     $this->_start_system_call($this->alias . '.' . $this->id . ' IN (' . $ids . ')');
                 }
                 $Result = $this->{$method_name}();
                 $this->_end_system_call();
             }
         }
         if (isset($Result)) {
             return $Result;
         }
     }
     return null;
 }
Ejemplo n.º 27
0
function make_username($name)
{
    # Generates a unique username for the given name
    # First compress the various name parts
    $s = trim_array(explode(" ", $name));
    $name = $s[count($s) - 1];
    for ($n = count($s) - 2; $n >= 0; $n--) {
        $name = substr($s[$n], 0, 1) . $name;
    }
    $name = safe_file_name(strtolower($name));
    # Create fullname usernames:
    global $user_account_fullname_create;
    if ($user_account_fullname_create) {
        $name = '';
        foreach ($s as $name_part) {
            $name .= '_' . $name_part;
        }
        $name = substr($name, 1);
        $name = safe_file_name($name);
    }
    # Check for uniqueness... append an ever-increasing number until unique.
    $unique = false;
    $num = -1;
    while (!$unique) {
        $num++;
        $c = sql_value("select count(*) value from user where username='******'", 0);
        $unique = $c == 0;
    }
    return $name . ($num == 0 ? "" : $num);
}
Ejemplo n.º 28
0
function update_rss_feed_real($link, $feed, $ignore_daemon = false)
{
    global $memcache;
    if (!$_REQUEST["daemon"] && !$ignore_daemon) {
        return false;
    }
    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
        _debug("update_rss_feed: start");
    }
    if (!$ignore_daemon) {
        if (DB_TYPE == "pgsql") {
            $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
        } else {
            $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
        }
        $result = db_query($link, "SELECT id,update_interval,auth_login,\n\t\t\t\tauth_pass,cache_images,update_method\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}' AND {$updstart_thresh_qpart}");
    } else {
        $result = db_query($link, "SELECT id,update_interval,auth_login,\n\t\t\t\tfeed_url,auth_pass,cache_images,update_method,last_updated\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
    }
    if (db_num_rows($result) == 0) {
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: feed {$feed} NOT FOUND/SKIPPED");
        }
        return false;
    }
    $update_method = db_fetch_result($result, 0, "update_method");
    $last_updated = db_fetch_result($result, 0, "last_updated");
    db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'");
    $auth_login = db_fetch_result($result, 0, "auth_login");
    $auth_pass = db_fetch_result($result, 0, "auth_pass");
    if (ALLOW_SELECT_UPDATE_METHOD) {
        if (ENABLE_SIMPLEPIE) {
            $use_simplepie = $update_method != 1;
        } else {
            $use_simplepie = $update_method == 2;
        }
    } else {
        $use_simplepie = ENABLE_SIMPLEPIE;
    }
    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
        _debug("use simplepie: {$use_simplepie} (feed setting: {$update_method})\n");
    }
    if (!$use_simplepie) {
        $auth_login = urlencode($auth_login);
        $auth_pass = urlencode($auth_pass);
    }
    $update_interval = db_fetch_result($result, 0, "update_interval");
    $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
    $fetch_url = db_fetch_result($result, 0, "feed_url");
    if ($update_interval < 0) {
        return;
    }
    $feed = db_escape_string($feed);
    if ($auth_login && $auth_pass) {
        $url_parts = array();
        preg_match("/(^[^:]*):\\/\\/(.*)/", $fetch_url, $url_parts);
        if ($url_parts[1] && $url_parts[2]) {
            $fetch_url = $url_parts[1] . "://{$auth_login}:{$auth_pass}@" . $url_parts[2];
        }
    }
    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
        _debug("update_rss_feed: fetching [{$fetch_url}]...");
    }
    if (!defined('DAEMON_EXTENDED_DEBUG') && !$_REQUEST['xdebug']) {
        error_reporting(0);
    }
    $obj_id = md5("FDATA:{$use_simplepie}:{$fetch_url}");
    if ($memcache && ($obj = $memcache->get($obj_id))) {
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: data found in memcache.");
        }
        $rss = $obj;
    } else {
        if (!$use_simplepie) {
            $rss = fetch_rss($fetch_url);
        } else {
            if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
                mkdir(SIMPLEPIE_CACHE_DIR);
            }
            $rss = new SimplePie();
            $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
            #			$rss->set_timeout(10);
            $rss->set_feed_url($fetch_url);
            $rss->set_output_encoding('UTF-8');
            if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("enabling image cache");
                }
                $rss->set_image_handler('./image.php', 'i');
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("feed update interval (sec): " . get_feed_update_interval($link, $feed) * 60);
            }
            if (is_dir(SIMPLEPIE_CACHE_DIR)) {
                $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
                $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
            }
            $rss->init();
        }
        if ($memcache && $rss) {
            $memcache->add($obj_id, $rss, 0, 300);
        }
    }
    //		print_r($rss);
    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
        _debug("update_rss_feed: fetch done, parsing...");
    } else {
        error_reporting(DEFAULT_ERROR_LEVEL);
    }
    $feed = db_escape_string($feed);
    if ($use_simplepie) {
        $fetch_ok = !$rss->error();
    } else {
        $fetch_ok = !!$rss;
    }
    if ($fetch_ok) {
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: processing feed data...");
        }
        //			db_query($link, "BEGIN");
        $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
        $registered_title = db_fetch_result($result, 0, "title");
        $orig_icon_url = db_fetch_result($result, 0, "icon_url");
        $orig_site_url = db_fetch_result($result, 0, "site_url");
        $owner_uid = db_fetch_result($result, 0, "owner_uid");
        if ($use_simplepie) {
            $site_url = $rss->get_link();
        } else {
            $site_url = $rss->channel["link"];
        }
        if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: checking favicon...");
            }
            check_feed_favicon($site_url, $feed, $link);
        }
        if (!$registered_title || $registered_title == "[Unknown]") {
            if ($use_simplepie) {
                $feed_title = db_escape_string($rss->get_title());
            } else {
                $feed_title = db_escape_string($rss->channel["title"]);
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: registering title: {$feed_title}");
            }
            db_query($link, "UPDATE ttrss_feeds SET \n\t\t\t\t\ttitle = '{$feed_title}' WHERE id = '{$feed}'");
        }
        // weird, weird Magpie
        if (!$use_simplepie) {
            if (!$site_url) {
                $site_url = db_escape_string($rss->channel["link_"]);
            }
        }
        if ($site_url && $orig_site_url != db_escape_string($site_url)) {
            db_query($link, "UPDATE ttrss_feeds SET \n\t\t\t\t\tsite_url = '{$site_url}' WHERE id = '{$feed}'");
        }
        //			print "I: " . $rss->channel["image"]["url"];
        if (!$use_simplepie) {
            $icon_url = $rss->image["url"];
        } else {
            $icon_url = $rss->get_image_url();
        }
        if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
            $icon_url = db_escape_string($icon_url);
            db_query($link, "UPDATE ttrss_feeds SET icon_url = '{$icon_url}' WHERE id = '{$feed}'");
        }
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: loading filters...");
        }
        $filters = load_filters($link, $feed, $owner_uid);
        if ($use_simplepie) {
            $iterator = $rss->get_items();
        } else {
            $iterator = $rss->items;
            if (!$iterator || !is_array($iterator)) {
                $iterator = $rss->entries;
            }
            if (!$iterator || !is_array($iterator)) {
                $iterator = $rss;
            }
        }
        if (!is_array($iterator)) {
            /* db_query($link, "UPDATE ttrss_feeds 
            			SET last_error = 'Parse error: can\'t find any articles.'
            			WHERE id = '$feed'"); */
            // clear any errors and mark feed as updated if fetched okay
            // even if it's blank
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: entry iterator is not an array, no articles?");
            }
            db_query($link, "UPDATE ttrss_feeds \n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
            return;
            // no articles
        }
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: processing articles...");
        }
        foreach ($iterator as $item) {
            if ($_REQUEST['xdebug'] == 2) {
                print_r($item);
            }
            if ($use_simplepie) {
                $entry_guid = $item->get_id();
                if (!$entry_guid) {
                    $entry_guid = $item->get_link();
                }
                if (!$entry_guid) {
                    $entry_guid = make_guid_from_title($item->get_title());
                }
            } else {
                $entry_guid = $item["id"];
                if (!$entry_guid) {
                    $entry_guid = $item["guid"];
                }
                if (!$entry_guid) {
                    $entry_guid = $item["link"];
                }
                if (!$entry_guid) {
                    $entry_guid = make_guid_from_title($item["title"]);
                }
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: guid {$entry_guid}");
            }
            if (!$entry_guid) {
                continue;
            }
            $entry_timestamp = "";
            if ($use_simplepie) {
                $entry_timestamp = strtotime($item->get_date());
            } else {
                $rss_2_date = $item['pubdate'];
                $rss_1_date = $item['dc']['date'];
                $atom_date = $item['issued'];
                if (!$atom_date) {
                    $atom_date = $item['updated'];
                }
                if ($atom_date != "") {
                    $entry_timestamp = parse_w3cdtf($atom_date);
                }
                if ($rss_1_date != "") {
                    $entry_timestamp = parse_w3cdtf($rss_1_date);
                }
                if ($rss_2_date != "") {
                    $entry_timestamp = strtotime($rss_2_date);
                }
            }
            if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
                $entry_timestamp = time();
                $no_orig_date = 'true';
            } else {
                $no_orig_date = 'false';
            }
            $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: date {$entry_timestamp} [{$entry_timestamp_fmt}]");
            }
            if ($use_simplepie) {
                $entry_title = $item->get_title();
            } else {
                $entry_title = trim(strip_tags($item["title"]));
            }
            if ($use_simplepie) {
                $entry_link = $item->get_link();
            } else {
                // strange Magpie workaround
                $entry_link = $item["link_"];
                if (!$entry_link) {
                    $entry_link = $item["link"];
                }
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: title {$entry_title}");
            }
            if (!$entry_title) {
                $entry_title = date("Y-m-d H:i:s", $entry_timestamp);
            }
            $entry_link = strip_tags($entry_link);
            if ($use_simplepie) {
                $entry_content = $item->get_content();
                if (!$entry_content) {
                    $entry_content = $item->get_description();
                }
            } else {
                $entry_content = $item["content:escaped"];
                if (!$entry_content) {
                    $entry_content = $item["content:encoded"];
                }
                if (!$entry_content) {
                    $entry_content = $item["content"]["encoded"];
                }
                if (!$entry_content) {
                    $entry_content = $item["content"];
                }
                // Magpie bugs are getting ridiculous
                if (trim($entry_content) == "Array") {
                    $entry_content = false;
                }
                if (!$entry_content) {
                    $entry_content = $item["atom_content"];
                }
                if (!$entry_content) {
                    $entry_content = $item["summary"];
                }
                if (!$entry_content || strlen($entry_content) < strlen($item["description"])) {
                    $entry_content = $item["description"];
                }
                // WTF
                if (is_array($entry_content)) {
                    $entry_content = $entry_content["encoded"];
                    if (!$entry_content) {
                        $entry_content = $entry_content["escaped"];
                    }
                }
            }
            if ($_REQUEST["xdebug"] == 2) {
                print "update_rss_feed: content: ";
                print_r(htmlspecialchars($entry_content));
            }
            $entry_content_unescaped = $entry_content;
            if ($use_simplepie) {
                $entry_comments = strip_tags($item->data["comments"]);
                if ($item->get_author()) {
                    $entry_author_item = $item->get_author();
                    $entry_author = $entry_author_item->get_name();
                    if (!$entry_author) {
                        $entry_author = $entry_author_item->get_email();
                    }
                    $entry_author = db_escape_string($entry_author);
                }
            } else {
                $entry_comments = strip_tags($item["comments"]);
                $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
                if ($item['author']) {
                    if (is_array($item['author'])) {
                        if (!$entry_author) {
                            $entry_author = db_escape_string(strip_tags($item['author']['name']));
                        }
                        if (!$entry_author) {
                            $entry_author = db_escape_string(strip_tags($item['author']['email']));
                        }
                    }
                    if (!$entry_author) {
                        $entry_author = db_escape_string(strip_tags($item['author']));
                    }
                }
            }
            if (preg_match('/^[\\t\\n\\r ]*$/', $entry_author)) {
                $entry_author = '';
            }
            $entry_guid = db_escape_string(strip_tags($entry_guid));
            $entry_guid = mb_substr($entry_guid, 0, 250);
            $result = db_query($link, "SELECT id FROM\tttrss_entries \n\t\t\t\t\tWHERE guid = '{$entry_guid}'");
            $entry_content = db_escape_string($entry_content);
            $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
            $entry_title = db_escape_string($entry_title);
            $entry_link = db_escape_string($entry_link);
            $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
            $entry_author = mb_substr($entry_author, 0, 250);
            if ($use_simplepie) {
                $num_comments = 0;
                #FIXME#
            } else {
                $num_comments = db_escape_string($item["slash"]["comments"]);
            }
            if (!$num_comments) {
                $num_comments = 0;
            }
            // parse <category> entries into tags
            if ($use_simplepie) {
                $additional_tags = array();
                $additional_tags_src = $item->get_categories();
                if (is_array($additional_tags_src)) {
                    foreach ($additional_tags_src as $tobj) {
                        array_push($additional_tags, $tobj->get_term());
                    }
                }
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: category tags:");
                    print_r($additional_tags);
                }
            } else {
                $t_ctr = $item['category#'];
                $additional_tags = false;
                if ($t_ctr == 0) {
                    $additional_tags = false;
                } else {
                    if ($t_ctr > 0) {
                        $additional_tags = array($item['category']);
                        if ($item['category@term']) {
                            array_push($additional_tags, $item['category@term']);
                        }
                        for ($i = 0; $i <= $t_ctr; $i++) {
                            if ($item["category#{$i}"]) {
                                array_push($additional_tags, $item["category#{$i}"]);
                            }
                            if ($item["category#{$i}@term"]) {
                                array_push($additional_tags, $item["category#{$i}@term"]);
                            }
                        }
                    }
                }
                // parse <dc:subject> elements
                $t_ctr = $item['dc']['subject#'];
                if ($t_ctr > 0) {
                    $additional_tags = array($item['dc']['subject']);
                    for ($i = 0; $i <= $t_ctr; $i++) {
                        if ($item['dc']["subject#{$i}"]) {
                            array_push($additional_tags, $item['dc']["subject#{$i}"]);
                        }
                    }
                }
            }
            // enclosures
            $enclosures = array();
            if ($use_simplepie) {
                $encs = $item->get_enclosures();
                if (is_array($encs)) {
                    foreach ($encs as $e) {
                        $e_item = array($e->link, $e->type, $e->length);
                        array_push($enclosures, $e_item);
                    }
                }
            } else {
                // <enclosure>
                $e_ctr = $item['enclosure#'];
                if ($e_ctr > 0) {
                    $e_item = array($item['enclosure@url'], $item['enclosure@type'], $item['enclosure@length']);
                    array_push($enclosures, $e_item);
                    for ($i = 0; $i <= $e_ctr; $i++) {
                        if ($item["enclosure#{$i}@url"]) {
                            $e_item = array($item["enclosure#{$i}@url"], $item["enclosure#{$i}@type"], $item["enclosure#{$i}@length"]);
                            array_push($enclosures, $e_item);
                        }
                    }
                }
                // <media:content>
                // can there be many of those? yes -fox
                $m_ctr = $item['media']['content#'];
                if ($m_ctr > 0) {
                    $e_item = array($item['media']['content@url'], $item['media']['content@medium'], $item['media']['content@length']);
                    array_push($enclosures, $e_item);
                    for ($i = 0; $i <= $m_ctr; $i++) {
                        if ($item["media"]["content#{$i}@url"]) {
                            $e_item = array($item["media"]["content#{$i}@url"], $item["media"]["content#{$i}@medium"], $item["media"]["content#{$i}@length"]);
                            array_push($enclosures, $e_item);
                        }
                    }
                }
            }
            # sanitize content
            $entry_content = sanitize_article_content($entry_content);
            $entry_title = sanitize_article_content($entry_title);
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: done collecting data [TITLE:{$entry_title}]");
            }
            db_query($link, "BEGIN");
            if (db_num_rows($result) == 0) {
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: base guid not found");
                }
                // base post entry does not exist, create it
                $result = db_query($link, "INSERT INTO ttrss_entries \n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}', \n\t\t\t\t\t\t\t'{$entry_guid}', \n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}', \n\t\t\t\t\t\t\t'{$entry_content}', \n\t\t\t\t\t\t\t'{$content_hash}',\n\t\t\t\t\t\t\t{$no_orig_date}, \n\t\t\t\t\t\t\tNOW(), \n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_author}')");
            } else {
                // we keep encountering the entry in feeds, so we need to
                // update date_entered column so that we don't get horrible
                // dupes when the entry gets purged and reinserted again e.g.
                // in the case of SLOW SLOW OMG SLOW updating feeds
                $base_entry_id = db_fetch_result($result, 0, "id");
                db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'");
            }
            // now it should exist, if not - bad luck then
            $result = db_query($link, "SELECT \n\t\t\t\t\t\tid,content_hash,no_orig_date,title,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(date_entered,1,19) as date_entered,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(updated,1,19) as updated,\n\t\t\t\t\t\tnum_comments\n\t\t\t\t\tFROM \n\t\t\t\t\t\tttrss_entries \n\t\t\t\t\tWHERE guid = '{$entry_guid}'");
            $entry_ref_id = 0;
            $entry_int_id = 0;
            if (db_num_rows($result) == 1) {
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: base guid found, checking for user record");
                }
                // this will be used below in update handler
                $orig_content_hash = db_fetch_result($result, 0, "content_hash");
                $orig_title = db_fetch_result($result, 0, "title");
                $orig_num_comments = db_fetch_result($result, 0, "num_comments");
                $orig_date_entered = strtotime(db_fetch_result($result, 0, "date_entered"));
                $ref_id = db_fetch_result($result, 0, "id");
                $entry_ref_id = $ref_id;
                // check for user post link to main table
                // do we allow duplicate posts with same GUID in different feeds?
                if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
                    $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)";
                } else {
                    $dupcheck_qpart = "";
                }
                //					error_reporting(0);
                $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author);
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: article filters: ");
                    if (count($article_filters) != 0) {
                        print_r($article_filters);
                    }
                }
                if (find_article_filter($article_filters, "filter")) {
                    db_query($link, "COMMIT");
                    // close transaction in progress
                    continue;
                }
                //					error_reporting (DEFAULT_ERROR_LEVEL);
                $score = calculate_article_score($article_filters);
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: initial score: {$score}");
                }
                $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}";
                //					if ($_REQUEST["xdebug"]) print "$query\n";
                $result = db_query($link, $query);
                // okay it doesn't exist - create user entry
                if (db_num_rows($result) == 0) {
                    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                        _debug("update_rss_feed: user record not found, creating...");
                    }
                    if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
                        $unread = 'true';
                        $last_read_qpart = 'NULL';
                    } else {
                        $unread = 'false';
                        $last_read_qpart = 'NOW()';
                    }
                    if (find_article_filter($article_filters, 'mark') || $score > 1000) {
                        $marked = 'true';
                    } else {
                        $marked = 'false';
                    }
                    if (find_article_filter($article_filters, 'publish')) {
                        $published = 'true';
                    } else {
                        $published = 'false';
                    }
                    $result = db_query($link, "INSERT INTO ttrss_user_entries \n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked, \n\t\t\t\t\t\t\t\t\tpublished, score) \n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}')");
                    $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1");
                    if (db_num_rows($result) == 1) {
                        $entry_int_id = db_fetch_result($result, 0, "int_id");
                    }
                } else {
                    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                        _debug("update_rss_feed: user record FOUND");
                    }
                    $entry_ref_id = db_fetch_result($result, 0, "ref_id");
                    $entry_int_id = db_fetch_result($result, 0, "int_id");
                }
                if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                    _debug("update_rss_feed: RID: {$entry_ref_id}, IID: {$entry_int_id}");
                }
                $post_needs_update = false;
                if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) && $content_hash != $orig_content_hash) {
                    //						print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
                    $post_needs_update = true;
                }
                if (db_escape_string($orig_title) != $entry_title) {
                    $post_needs_update = true;
                }
                if ($orig_num_comments != $num_comments) {
                    $post_needs_update = true;
                }
                //					this doesn't seem to be very reliable
                //
                //					if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
                //						$post_needs_update = true;
                //					}
                // if post needs update, update it and mark all user entries
                // linking to this post as updated
                if ($post_needs_update) {
                    if (defined('DAEMON_EXTENDED_DEBUG')) {
                        _debug("update_rss_feed: post {$entry_guid} needs update...");
                    }
                    //						print "<!-- post $orig_title needs update : $post_needs_update -->";
                    db_query($link, "UPDATE ttrss_entries \n\t\t\t\t\t\t\tSET title = '{$entry_title}', content = '{$entry_content}',\n\t\t\t\t\t\t\t\tcontent_hash = '{$content_hash}',\n\t\t\t\t\t\t\t\tnum_comments = '{$num_comments}'\n\t\t\t\t\t\t\tWHERE id = '{$ref_id}'");
                    if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
                        db_query($link, "UPDATE ttrss_user_entries \n\t\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'");
                    } else {
                        db_query($link, "UPDATE ttrss_user_entries \n\t\t\t\t\t\t\t\tSET last_read = null WHERE ref_id = '{$ref_id}' AND unread = false");
                    }
                }
            }
            db_query($link, "COMMIT");
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: assigning labels...");
            }
            assign_article_to_labels($link, $entry_ref_id, $article_filters, $owner_uid);
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: looking for enclosures...");
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                print_r($enclosures);
            }
            db_query($link, "BEGIN");
            foreach ($enclosures as $enc) {
                $enc_url = db_escape_string($enc[0]);
                $enc_type = db_escape_string($enc[1]);
                $enc_dur = db_escape_string($enc[2]);
                $result = db_query($link, "SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'");
                if (db_num_rows($result) == 0) {
                    db_query($link, "INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '', '{$enc_dur}', '{$entry_ref_id}')");
                }
            }
            db_query($link, "COMMIT");
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: looking for tags...");
            }
            /* taaaags */
            // <a href="..." rel="tag">Xorg</a>, //
            $entry_tags = null;
            preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\\/a>/i", $entry_content_unescaped, $entry_tags);
            /*				print "<p><br/>$entry_title : $entry_content_unescaped<br>";
            				print_r($entry_tags);
            				print "<br/></p>"; */
            $entry_tags = $entry_tags[1];
            # check for manual tags
            foreach ($article_filters as $f) {
                if ($f[0] == "tag") {
                    $manual_tags = trim_array(split(",", $f[1]));
                    foreach ($manual_tags as $tag) {
                        if (tag_is_valid($tag)) {
                            array_push($entry_tags, $tag);
                        }
                    }
                }
            }
            $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link, 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
            if ($additional_tags && is_array($additional_tags)) {
                foreach ($additional_tags as $tag) {
                    if (tag_is_valid($tag) && array_search($tag, $boring_tags) === FALSE) {
                        array_push($entry_tags, $tag);
                    }
                }
            }
            //				print "<p>TAGS: "; print_r($entry_tags); print "</p>";
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                print_r($entry_tags);
            }
            if (count($entry_tags) > 0) {
                db_query($link, "BEGIN");
                foreach ($entry_tags as $tag) {
                    $tag = sanitize_tag($tag);
                    $tag = db_escape_string($tag);
                    if (!tag_is_valid($tag)) {
                        continue;
                    }
                    $result = db_query($link, "SELECT id FROM ttrss_tags\t\t\n\t\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND \n\t\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1");
                    //						print db_fetch_result($result, 0, "id");
                    if ($result && db_num_rows($result) == 0) {
                        db_query($link, "INSERT INTO ttrss_tags \n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')");
                    }
                }
                db_query($link, "COMMIT");
            }
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: article processed");
            }
        }
        if (!$last_updated) {
            if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
                _debug("update_rss_feed: new feed, catching it up...");
            }
            catchup_feed($link, $feed, false, $owner_uid);
        }
        purge_feed($link, $feed, 0);
        db_query($link, "UPDATE ttrss_feeds \n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
        //			db_query($link, "COMMIT");
    } else {
        if ($use_simplepie) {
            $error_msg = mb_substr($rss->error(), 0, 250);
        } else {
            $error_msg = mb_substr(magpie_error(), 0, 250);
        }
        if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
            _debug("update_rss_feed: error fetching feed: {$error_msg}");
        }
        $error_msg = db_escape_string($error_msg);
        db_query($link, "UPDATE ttrss_feeds SET last_error = '{$error_msg}', \n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
    }
    if ($use_simplepie) {
        unset($rss);
    }
    if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
        _debug("update_rss_feed: done");
    }
}
Ejemplo n.º 29
0
<div class="Question"><label><?php 
echo $lang["licensor_licensee"];
?>
</label><input type=text class="stdwidth" name="holder" id="holder" value="<?php 
echo htmlspecialchars($license["holder"]);
?>
" />
<div class="clearerleft"> </div></div>

<div class="Question"><label><?php 
echo $lang["indicateusagemedium"];
?>
</label>
<?php 
$s = trim_array(explode(",", $license["license_usage"]));
foreach ($license_usage_mediums as $medium) {
    ?>
	<input type="checkbox" name="license_usage[]" value="<?php 
    echo $medium;
    ?>
" <?php 
    if (in_array($medium, $s)) {
        ?>
checked<?php 
    }
    ?>
>&nbsp;<?php 
    echo lang_or_i18n_get_translated($medium, "license_usage-");
    ?>
	&nbsp;
function filter_match($filter, $name, $value)
{
    # In the given filter string, does name/value match?
    # Returns:
    # 0 = no match for name
    # 1 = matched name but value was not present
    # 2 = matched name and value was correct
    $s = explode(";", $filter);
    foreach ($s as $condition) {
        $s = explode("=", $condition);
        # Support for "NOT" matching. Return results only where the specified value or values are NOT set.
        $checkname = $s[0];
        $filter_not = false;
        if (substr($checkname, -1) == "!") {
            $filter_not = true;
            $checkname = substr($checkname, 0, -1);
            # Strip off the exclamation mark.
        }
        if ($checkname == $name) {
            $checkvalues = $s[1];
            $s = explode("|", strtoupper($checkvalues));
            $v = trim_array(explode(",", strtoupper($value)));
            foreach ($s as $checkvalue) {
                if (in_array($checkvalue, $v)) {
                    return $filter_not ? 1 : 2;
                }
            }
            return $filter_not ? 2 : 1;
        }
    }
    return 0;
}